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,491 | Make method extensions | No need for these to be instance methods on ABstractSyntaxFacts | CyrusNajmabadi | "2021-09-17T20:59:25Z" | "2021-09-18T00:30:21Z" | a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d | b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6 | Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts | ./src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnostic.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics
{
internal class XamlDiagnostic
{
public string? Code { get; set; }
public string? Message { get; set; }
public XamlDiagnosticSeverity Severity { get; set; }
public int Offset { get; set; }
public int Length { get; set; }
public string? Tool { get; set; }
public string? ExtendedMessage { get; set; }
public string? HelpLink { get; set; }
public string[]? CustomTags { get; set; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics
{
internal class XamlDiagnostic
{
public string? Code { get; set; }
public string? Message { get; set; }
public XamlDiagnosticSeverity Severity { get; set; }
public int Offset { get; set; }
public int Length { get; set; }
public string? Tool { get; set; }
public string? ExtendedMessage { get; set; }
public string? HelpLink { get; set; }
public string[]? CustomTags { get; set; }
}
}
| -1 |
dotnet/roslyn | 56,491 | Make method extensions | No need for these to be instance methods on ABstractSyntaxFacts | CyrusNajmabadi | "2021-09-17T20:59:25Z" | "2021-09-18T00:30:21Z" | a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d | b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6 | Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts | ./src/Compilers/VisualBasic/Test/Semantic/Binding/LookupTests.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.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class LookupTests
Inherits BasicTestBase
Private Function GetContext(compilation As VisualBasicCompilation,
treeName As String,
textToFind As String) As Binder
Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName)
Dim position = CompilationUtils.FindPositionFromText(tree, textToFind)
Return DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel).GetEnclosingBinder(position)
End Function
<Fact()>
Public Sub TestLookupResult()
Dim sym1 = New MockAssemblySymbol("hello") ' just a symbol to put in results
Dim sym2 = New MockAssemblySymbol("goodbye") ' just a symbol to put in results
Dim sym3 = New MockAssemblySymbol("world") ' just a symbol to put in results
Dim sym4 = New MockAssemblySymbol("banana") ' just a symbol to put in results
Dim sym5 = New MockAssemblySymbol("apple") ' just a symbol to put in results
Dim meth1 = New MockMethodSymbol("goo") ' just a symbol to put in results
Dim meth2 = New MockMethodSymbol("bag") ' just a symbol to put in results
Dim meth3 = New MockMethodSymbol("baz") ' just a symbol to put in results
Dim r1 = New LookupResult()
r1.SetFrom(SingleLookupResult.Empty)
Assert.False(r1.HasSymbol)
Assert.False(r1.IsGood)
Assert.False(r1.HasDiagnostic)
Assert.False(r1.StopFurtherLookup)
Dim r2 = SingleLookupResult.Good(sym1)
Dim _r2 = New LookupResult()
_r2.SetFrom(r2)
Assert.True(_r2.HasSymbol)
Assert.True(_r2.IsGood)
Assert.Same(sym1, _r2.SingleSymbol)
Assert.False(_r2.HasDiagnostic)
Assert.True(_r2.StopFurtherLookup)
Dim r3 = New LookupResult()
r3.SetFrom(SingleLookupResult.Ambiguous(ImmutableArray.Create(Of Symbol)(sym1, sym2, sym3), AddressOf GenerateAmbiguity))
Assert.True(r3.HasSymbol)
Assert.False(r3.IsGood)
Assert.Same(sym1, r3.SingleSymbol)
Assert.True(r3.HasDiagnostic)
Assert.True(r3.StopFurtherLookup)
Dim diag3 = DirectCast(r3.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Same(sym1, diag3.AmbiguousSymbols.Item(0))
Assert.Same(sym2, diag3.AmbiguousSymbols.Item(1))
Assert.Same(sym3, diag3.AmbiguousSymbols.Item(2))
Dim r4 = New LookupResult()
r4.SetFrom(SingleLookupResult.Inaccessible(sym2, New BadSymbolDiagnostic(sym2, ERRID.ERR_InaccessibleSymbol2, sym2)))
Assert.True(r4.HasSymbol)
Assert.False(r4.IsGood)
Assert.Same(sym2, r4.SingleSymbol)
Assert.True(r4.HasDiagnostic)
Assert.False(r4.StopFurtherLookup)
Dim diag4 = DirectCast(r4.Diagnostic, BadSymbolDiagnostic)
Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag4.Code)
Assert.Same(sym2, diag4.BadSymbol)
Dim r5 = New LookupResult()
r5.SetFrom(SingleLookupResult.WrongArity(sym3, ERRID.ERR_IndexedNotArrayOrProc))
Assert.True(r5.HasSymbol)
Assert.False(r5.IsGood)
Assert.Same(sym3, r5.SingleSymbol)
Assert.True(r5.HasDiagnostic)
Assert.False(r5.StopFurtherLookup)
Dim diag5 = r5.Diagnostic
Assert.Equal(ERRID.ERR_IndexedNotArrayOrProc, diag5.Code)
Dim r6 = New LookupResult()
r6.MergePrioritized(r1)
r6.MergePrioritized(r2)
Assert.True(r6.HasSymbol)
Assert.Same(sym1, r6.SingleSymbol)
Assert.False(r6.HasDiagnostic)
Assert.True(r6.StopFurtherLookup)
r6.Free()
Dim r7 = New LookupResult()
r7.MergePrioritized(r2)
r7.MergePrioritized(r1)
Assert.True(r7.HasSymbol)
Assert.Same(sym1, r7.SingleSymbol)
Assert.False(r7.HasDiagnostic)
Assert.True(r7.StopFurtherLookup)
Dim r8 = New LookupResult()
r8.SetFrom(SingleLookupResult.Good(sym4))
Dim r9 = New LookupResult()
r9.SetFrom(r2)
r9.MergePrioritized(r8)
Assert.True(r9.HasSymbol)
Assert.Same(sym1, r9.SingleSymbol)
Assert.False(r9.HasDiagnostic)
Assert.True(r9.StopFurtherLookup)
Dim r10 = New LookupResult()
r10.SetFrom(r3)
r10.MergePrioritized(r8)
r10.MergePrioritized(r2)
Assert.True(r10.HasSymbol)
Assert.Same(sym1, r10.SingleSymbol)
Assert.True(r10.HasDiagnostic)
Assert.True(r10.StopFurtherLookup)
Dim diag10 = DirectCast(r10.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Same(sym1, diag10.AmbiguousSymbols.Item(0))
Assert.Same(sym2, diag10.AmbiguousSymbols.Item(1))
Assert.Same(sym3, diag10.AmbiguousSymbols.Item(2))
Dim r11 = New LookupResult()
r11.MergePrioritized(r1)
r11.MergePrioritized(r5)
r11.MergePrioritized(r3)
r11.MergePrioritized(r8)
r11.MergePrioritized(r2)
Assert.True(r11.HasSymbol)
Assert.Same(sym1, r11.SingleSymbol)
Assert.True(r11.HasDiagnostic)
Assert.True(r11.StopFurtherLookup)
Dim diag11 = DirectCast(r11.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Same(sym1, diag11.AmbiguousSymbols.Item(0))
Assert.Same(sym2, diag11.AmbiguousSymbols.Item(1))
Assert.Same(sym3, diag11.AmbiguousSymbols.Item(2))
Dim r12 = New LookupResult()
Dim r12Empty = New LookupResult()
r12.MergePrioritized(r1)
r12.MergePrioritized(r12Empty)
Assert.False(r12.HasSymbol)
Assert.False(r12.HasDiagnostic)
Assert.False(r12.StopFurtherLookup)
Dim r13 = New LookupResult()
r13.MergePrioritized(r1)
r13.MergePrioritized(r5)
r13.MergePrioritized(r4)
Assert.True(r13.HasSymbol)
Assert.Same(sym2, r13.SingleSymbol)
Assert.True(r13.HasDiagnostic)
Assert.False(r13.StopFurtherLookup)
Dim diag13 = DirectCast(r13.Diagnostic, BadSymbolDiagnostic)
Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag13.Code)
Assert.Same(sym2, diag13.BadSymbol)
Dim r14 = New LookupResult()
r14.MergeAmbiguous(r1, AddressOf GenerateAmbiguity)
r14.MergeAmbiguous(r5, AddressOf GenerateAmbiguity)
r14.MergeAmbiguous(r4, AddressOf GenerateAmbiguity)
Assert.True(r14.HasSymbol)
Assert.Same(sym2, r14.SingleSymbol)
Assert.True(r14.HasDiagnostic)
Assert.False(r14.StopFurtherLookup)
Dim diag14 = DirectCast(r14.Diagnostic, BadSymbolDiagnostic)
Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag14.Code)
Assert.Same(sym2, diag14.BadSymbol)
Dim r15 = New LookupResult()
r15.MergeAmbiguous(r1, AddressOf GenerateAmbiguity)
r15.MergeAmbiguous(r8, AddressOf GenerateAmbiguity)
r15.MergeAmbiguous(r3, AddressOf GenerateAmbiguity)
r15.MergeAmbiguous(r14, AddressOf GenerateAmbiguity)
Assert.True(r15.HasSymbol)
Assert.Same(sym4, r15.SingleSymbol)
Assert.True(r15.HasDiagnostic)
Assert.True(r15.StopFurtherLookup)
Dim diag15 = DirectCast(r15.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Same(sym4, diag15.AmbiguousSymbols.Item(0))
Assert.Same(sym1, diag15.AmbiguousSymbols.Item(1))
Assert.Same(sym2, diag15.AmbiguousSymbols.Item(2))
Assert.Same(sym3, diag15.AmbiguousSymbols.Item(3))
Dim r16 = SingleLookupResult.Good(meth1)
Dim r17 = SingleLookupResult.Good(meth2)
Dim r18 = SingleLookupResult.Good(meth3)
Dim r19 = New LookupResult()
r19.MergeMembersOfTheSameType(r16, False)
Assert.True(r19.StopFurtherLookup)
Assert.Equal(1, r19.Symbols.Count)
Assert.False(r19.HasDiagnostic)
r19.MergeMembersOfTheSameType(r17, False)
Assert.True(r19.StopFurtherLookup)
Assert.Equal(2, r19.Symbols.Count)
Assert.False(r19.HasDiagnostic)
r19.MergeMembersOfTheSameType(r18, False)
Assert.True(r19.StopFurtherLookup)
Assert.Equal(3, r19.Symbols.Count)
Assert.Equal(r16.Symbol, r19.Symbols(0))
Assert.Equal(r17.Symbol, r19.Symbols(1))
Assert.Equal(r18.Symbol, r19.Symbols(2))
Assert.False(r19.HasDiagnostic)
r19.MergeAmbiguous(r2, AddressOf GenerateAmbiguity)
Assert.True(r19.StopFurtherLookup)
Assert.Equal(1, r19.Symbols.Count)
Assert.Equal(r16.Symbol, r19.SingleSymbol)
Assert.True(r19.HasDiagnostic)
Dim diag19 = DirectCast(r19.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Equal(4, diag19.AmbiguousSymbols.Length)
Assert.Equal(r16.Symbol, diag19.AmbiguousSymbols(0))
Assert.Equal(r17.Symbol, diag19.AmbiguousSymbols(1))
Assert.Equal(r18.Symbol, diag19.AmbiguousSymbols(2))
Assert.Equal(r2.Symbol, diag19.AmbiguousSymbols(3))
End Sub
Private Function GenerateAmbiguity(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic
Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInModules2, syms, New FormattedSymbolList(syms.AsEnumerable))
End Function
<Fact()>
Public Sub MemberLookup1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Comp">
<file name="a.vb">
Option Strict On
Option Explicit On
Class A
Public Class M3(Of T)
End Class
Public Overloads Sub M4(ByVal x As Integer, ByVal y As Integer)
End Sub
Public Overloads Sub M5(ByVal x As Integer, ByVal y As Integer)
End Sub
End Class
Class B
Inherits A
Public Shared Sub M1(Of T)()
End Sub
Public Shared Sub M2()
End Sub
Public Shadows M3 As Integer
Public Overloads Sub M4(ByVal x As Integer, ByVal y As String)
End Sub
Public Shadows Sub M5(ByVal x As Integer, ByVal y As String)
End Sub
End Class
Class C
Inherits B
Public Shadows Class M1
End Class
Public Shadows Class M2(Of T)
End Class
Public Overloads Sub M4()
End Sub
Public Overloads Sub M4(ByVal x As Integer)
End Sub
Public Overloads Sub M5()
End Sub
Public Overloads Sub M5(ByVal x As Integer)
End Sub
End Class
Module Module1
Sub Main()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
Dim context = GetContext(compilation, "a.vb", "Sub Main")
Dim globalNS = compilation.GlobalNamespace
Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol)
Dim classB = DirectCast(globalNS.GetMembers("B").Single(), NamedTypeSymbol)
Dim classC = DirectCast(globalNS.GetMembers("C").Single(), NamedTypeSymbol)
Dim classA_M3 = DirectCast(classA.GetMembers("M3").Single(), NamedTypeSymbol)
Dim methA_M4 = DirectCast(classA.GetMembers("M4").Single(), MethodSymbol)
Dim methA_M5 = DirectCast(classA.GetMembers("M5").Single(), MethodSymbol)
Dim methB_M1 = DirectCast(classB.GetMembers("M1").Single(), MethodSymbol)
Dim methB_M2 = DirectCast(classB.GetMembers("M2").Single(), MethodSymbol)
Dim methB_M4 = DirectCast(classB.GetMembers("M4").Single(), MethodSymbol)
Dim methB_M5 = DirectCast(classB.GetMembers("M5").Single(), MethodSymbol)
Dim fieldB_M3 = DirectCast(classB.GetMembers("M3").Single(), FieldSymbol)
Dim classC_M1 = DirectCast(classC.GetMembers("M1").Single(), NamedTypeSymbol)
Dim classC_M2 = DirectCast(classC.GetMembers("M2").Single(), NamedTypeSymbol)
Dim methC_M4_0 = DirectCast(classC.GetMembers("M4")(0), MethodSymbol)
Dim methC_M4_1 = DirectCast(classC.GetMembers("M4")(1), MethodSymbol)
Dim methC_M5_0 = DirectCast(classC.GetMembers("M5")(0), MethodSymbol)
Dim methC_M5_1 = DirectCast(classC.GetMembers("M5")(1), MethodSymbol)
Dim lr As LookupResult
' nothing found
lr = New LookupResult()
context.LookupMember(lr, classC, "fizzle", 0, Nothing, Nothing)
Assert.Equal(LookupResultKind.Empty, lr.Kind)
' non-generic class shadows with arity 0
lr = New LookupResult()
context.LookupMember(lr, classC, "M1", 0, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(classC_M1, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
' method found with arity 1
lr = New LookupResult()
context.LookupMember(lr, classC, "M1", 1, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(methB_M1, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
' generic class shadows with arity 1
lr = New LookupResult()
context.LookupMember(lr, classC, "M2", 1, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(classC_M2, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
' method found with arity 0
lr = New LookupResult()
context.LookupMember(lr, classC, "M2", 0, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(methB_M2, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
' field shadows with arity 1
lr = New LookupResult()
context.LookupMember(lr, classC, "M3", 1, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(fieldB_M3, lr.Symbols.Single())
Assert.True(lr.HasDiagnostic)
' should collection all overloads of M4
lr = New LookupResult()
context.LookupMember(lr, classC, "M4", 1, LookupOptions.AllMethodsOfAnyArity, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(4, lr.Symbols.Count)
Assert.Contains(methA_M4, lr.Symbols)
Assert.Contains(methB_M4, lr.Symbols)
Assert.Contains(methC_M4_0, lr.Symbols)
Assert.Contains(methC_M4_1, lr.Symbols)
Assert.False(lr.HasDiagnostic)
' shouldn't get A.M5 because B.M5 is marked Shadows
lr = New LookupResult()
context.LookupMember(lr, classC, "M5", 1, LookupOptions.AllMethodsOfAnyArity, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(3, lr.Symbols.Count)
Assert.DoesNotContain(methA_M5, lr.Symbols)
Assert.Contains(methB_M5, lr.Symbols)
Assert.Contains(methC_M5_0, lr.Symbols)
Assert.Contains(methC_M5_1, lr.Symbols)
Assert.False(lr.HasDiagnostic)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact()>
Public Sub Bug3024()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug3024">
<file name="a.vb">
Imports P
Imports R
Module C
Dim x As Q
End Module
Namespace R
Module M
Class Q
End Class
End Module
End Namespace
Namespace P.Q
End Namespace
</file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
Assert.Same(compilation.GetTypeByMetadataName("R.M+Q"), compilation.GetTypeByMetadataName("C").GetMembers("x").OfType(Of FieldSymbol)().Single().Type)
End Sub
<Fact()>
Public Sub Bug3025()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug3025">
<file name="a.vb">
Imports P
Imports R
Module C
Dim x As Q
End Module
Namespace R
Module M
Class Q
End Class
End Module
End Namespace
Namespace P.Q
Class Z
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30182: Type expected.
Dim x As Q
~
</expected>)
End Sub
<Fact()>
Public Sub Bug4099()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4099">
<file name="a.vb">
Imports N
Imports K
Namespace N
Module M
Class C
End Class
End Module
End Namespace
Namespace K
Class C
End Class
End Namespace
Class A
Inherits C
End Class
</file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
Assert.Same(compilation.GetTypeByMetadataName("K.C"), compilation.GetTypeByMetadataName("A").BaseType)
End Sub
<Fact()>
Public Sub Bug4100()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug4100">
<file name="a.vb">
Imports N
Imports K
Namespace N
Class C
End Class
End Namespace
Namespace K
Namespace C
Class D
End Class
End Namespace
End Namespace
Class A
Inherits C
End Class
</file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
Assert.Same(compilation.GetTypeByMetadataName("N.C"), compilation.GetTypeByMetadataName("A").BaseType)
compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug4100">
<file name="a.vb">
Imports K
Imports N
Namespace N
Class C
End Class
End Namespace
Namespace K
Namespace C
Class D
End Class
End Namespace
End Namespace
Class A
Inherits C
End Class
</file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
Assert.Same(compilation.GetTypeByMetadataName("N.C"), compilation.GetTypeByMetadataName("A").BaseType)
End Sub
<Fact()>
Public Sub Bug3015()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug3015">
<file name="a.vb">
Imports P
Imports R
Module Module1
Sub Main()
Dim x As Q = New Q()
System.Console.WriteLine(x.GetType())
End Sub
End Module
Namespace R
Class Q
End Class
End Namespace
Namespace P.Q
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
R.Q
]]>)
End Sub
<Fact()>
Public Sub Bug3014()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug3014">
<file name="a.vb">
Imports P = System
Imports R
Module C
Sub Main()
Dim x As P(Of Integer)
x=Nothing
End Sub
End Module
Namespace R
Class P(Of T)
End Class
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32045: 'System' has no type parameters and so cannot have type arguments.
Dim x As P(Of Integer)
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AmbiguityInImports()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguityInImports1">
<file name="a.vb">
Namespace NS1
Friend Class CT1
End Class
Friend Class CT2
End Class
Public Class CT3(Of T)
End Class
Public Class CT4
End Class
Public Module M1
Friend Class CT1
End Class
Public Class CT2(Of T)
End Class
Public Class CT3
End Class
End Module
Public Module M2
Public Class CT3
End Class
End Module
End Namespace
Namespace NS2
Public Class CT5
End Class
Public Module M3
Public Class CT5
End Class
End Module
End Namespace
Namespace NS3
Public Class CT5
End Class
End Namespace
</file>
</compilation>)
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguityInImports3">
<file name="a.vb">
Namespace NS1
Namespace CT4
End Namespace
End Namespace
Namespace NS2
Namespace CT5
End Namespace
End Namespace
</file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="AmbiguityInImports2">
<file name="a.vb">
Imports NS2
Imports NS3
Namespace NS1
Module Module1
Sub Test()
Dim x1 As CT1
Dim x2 As CT2
Dim x3 As CT3
Dim x4 As CT4
Dim x5 As CT5
x1 = Nothing
x2 = Nothing
x3 = Nothing
x4 = Nothing
x5 = Nothing
End Sub
End Module
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1),
New VisualBasicCompilationReference(compilation3)})
CompilationUtils.AssertTheseDiagnostics(compilation2,
<expected>
BC30389: 'NS1.CT1' is not accessible in this context because it is 'Friend'.
Dim x1 As CT1
~~~
BC30389: 'NS1.CT2' is not accessible in this context because it is 'Friend'.
Dim x2 As CT2
~~~
BC30562: 'CT3' is ambiguous between declarations in Modules 'NS1.M1, NS1.M2'.
Dim x3 As CT3
~~~
BC30560: 'CT4' is ambiguous in the namespace 'NS1'.
Dim x4 As CT4
~~~
BC30560: 'CT5' is ambiguous in the namespace 'NS2'.
Dim x5 As CT5
~~~
</expected>)
End Sub
<Fact()>
Public Sub TieBreakingInImports()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TieBreakingInImports1">
<file name="a.vb">
Namespace NS1
Namespace Test1
Public Class Test3
End Class
End Namespace
Public Class Test2
End Class
Public Class Test5
End Class
End Namespace
Namespace NS2
Namespace Test1
Public Class Test4
End Class
End Namespace
Public Class Test5
End Class
End Namespace
</file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TieBreakingInImports2">
<file name="a.vb">
Namespace NS3
Class Test1
End Class
Class Test1(Of T)
End Class
Class Test5
End Class
End Namespace
</file>
</compilation>)
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TieBreakingInImports3">
<file name="a.vb">
Namespace NS2
Class Test2(Of T)
End Class
End Namespace
</file>
</compilation>)
Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="TieBreakingInImports4">
<file name="a.vb">
Imports NS1
Imports NS2
Imports NS3
Module Test
Sub Test()
Dim x1 As Test1 = Nothing
Dim x2 As Test1(Of Integer) = Nothing
Dim x3 As Test2(Of Integer) = Nothing
Dim x4 As Test5 = Nothing
End Sub
End Module
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1),
New VisualBasicCompilationReference(compilation2),
New VisualBasicCompilationReference(compilation3)})
CompilationUtils.AssertTheseDiagnostics(compilation4,
<expected>
BC30182: Type expected.
Dim x1 As Test1 = Nothing
~~~~~
BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'.
Dim x2 As Test1(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'.
Dim x3 As Test2(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS1, NS2'.
Dim x4 As Test5 = Nothing
~~~~~
</expected>)
Dim compilation5 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="TieBreakingInImports4">
<file name="a.vb">
Imports NS2
Imports NS3
Imports NS1
Module Test
Sub Test()
Dim x1 As Test1 = Nothing
Dim x2 As Test1(Of Integer) = Nothing
Dim x3 As Test2(Of Integer) = Nothing
Dim x4 As Test5 = Nothing
End Sub
End Module
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1),
New VisualBasicCompilationReference(compilation2),
New VisualBasicCompilationReference(compilation3)})
CompilationUtils.AssertTheseDiagnostics(compilation5,
<expected>
BC30182: Type expected.
Dim x1 As Test1 = Nothing
~~~~~
BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'.
Dim x2 As Test1(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'.
Dim x3 As Test2(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS2, NS1'.
Dim x4 As Test5 = Nothing
~~~~~
</expected>)
Dim compilation6 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="TieBreakingInImports4">
<file name="a.vb">
Imports NS3
Imports NS1
Imports NS2
Module Test
Sub Test()
Dim x1 As Test1 = Nothing
Dim x2 As Test1(Of Integer) = Nothing
Dim x3 As Test2(Of Integer) = Nothing
Dim x4 As Test5 = Nothing
End Sub
End Module
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1),
New VisualBasicCompilationReference(compilation2),
New VisualBasicCompilationReference(compilation3)})
CompilationUtils.AssertTheseDiagnostics(compilation6,
<expected>
BC30182: Type expected.
Dim x1 As Test1 = Nothing
~~~~~
BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'.
Dim x2 As Test1(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'.
Dim x3 As Test2(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS1, NS2'.
Dim x4 As Test5 = Nothing
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RecursiveCheckForAccessibleTypesWithinANamespace()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RecursiveCheckForAccessibleTypesWithinANamespace1">
<file name="a.vb">
Imports P
Module Module1
Sub Main()
Dim x As Q.R.S = New Q.R.S()
System.Console.WriteLine(x.GetType())
End Sub
End Module
Namespace P
Namespace Q
Namespace R
Public Class S
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
P.Q.R.S
]]>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RecursiveCheckForAccessibleTypesWithinANamespace2">
<file name="a.vb">
Imports P
Module Module1
Sub Main()
Dim x As Q.R.S = New Q.R.S()
System.Console.WriteLine(x.GetType())
End Sub
End Module
Namespace P
Namespace Q
Namespace R
Friend Class S
End Class
Friend Class T
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
P.Q.R.S
]]>)
End Sub
<Fact()>
Public Sub DoNotLoadTypesForAccessibilityOfMostAccessibleTypeWithinANamespace()
' We need to be careful about metadata references we use here.
' The test checks that fields of namespace symbols are initialized in certain order.
' If we used a shared Mscorlib reference then other tests might have already initialized it's shared AssemblySymbol.
Dim nonSharedMscorlibReference = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display:="mscorlib.v4_0_30319.dll")
Dim c = VisualBasicCompilation.Create("DoNotLoadTypesForAccessibilityOfMostAccessibleTypeWithinANamespace",
syntaxTrees:={Parse(<text>
Namespace P
End Namespace
</text>.Value)},
references:={nonSharedMscorlibReference})
Dim system = c.Assembly.Modules(0).GetReferencedAssemblySymbols()(0).GlobalNamespace.GetMembers("System").OfType(Of PENamespaceSymbol)().Single()
Dim deployment = system.GetMembers("Deployment").OfType(Of PENamespaceSymbol)().Single()
Dim internal = deployment.GetMembers("Internal").OfType(Of PENamespaceSymbol)().Single()
Dim isolation = internal.GetMembers("Isolation").OfType(Of PENamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, deployment.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, internal.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, isolation.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.False(isolation.AreTypesLoaded)
Assert.Equal(Accessibility.Friend, isolation.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.False(isolation.AreTypesLoaded)
Assert.Equal(Accessibility.Friend, isolation.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, deployment.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, internal.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
isolation.GetTypeMembers()
Assert.True(isolation.AreTypesLoaded)
Dim io = system.GetMembers("IO").OfType(Of PENamespaceSymbol)().Single()
Dim isolatedStorage = io.GetMembers("IsolatedStorage").OfType(Of PENamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, io.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, isolatedStorage.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.False(isolatedStorage.AreTypesLoaded)
Assert.Equal(Accessibility.Public, isolatedStorage.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.False(isolatedStorage.AreTypesLoaded)
Assert.Equal(Accessibility.Public, isolatedStorage.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Public, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Public, io.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
End Sub
<Fact()>
Public Sub TestMergedNamespaceContainsTypesAccessibleFrom()
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C1">
<file name="a.vb">
Namespace P
Namespace Q
Public Class R
End Class
End Namespace
End Namespace
</file>
</compilation>)
Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C2">
<file name="a.vb">
Namespace P
Namespace Q
Friend Class S
End Class
End Namespace
End Namespace
</file>
</compilation>)
Dim c3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace P
Namespace Q
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(c1), New VisualBasicCompilationReference(c2)})
Dim p = c3.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single()
Dim q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(0, p.RawContainsAccessibleTypes)
Assert.Equal(0, q.RawContainsAccessibleTypes)
Assert.Equal(Accessibility.Public, q.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Public, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Public, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(0, p.RawContainsAccessibleTypes)
Assert.Equal(0, q.RawContainsAccessibleTypes)
Assert.True(q.ContainsTypesAccessibleFrom(c3.Assembly))
Assert.True(p.ContainsTypesAccessibleFrom(c3.Assembly))
Assert.Equal(0, p.RawContainsAccessibleTypes)
Assert.Equal(0, q.RawContainsAccessibleTypes)
c3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace P
Namespace Q
Friend Class U
End Class
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(c2)})
p = c3.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single()
q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes)
Assert.True(q.ContainsTypesAccessibleFrom(c3.Assembly))
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.True, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.True, q.RawContainsAccessibleTypes)
Assert.True(p.ContainsTypesAccessibleFrom(c3.Assembly))
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Dim c4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="C4">
<file name="a.vb">
Namespace P
Namespace Q
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(c3), New VisualBasicCompilationReference(c2)})
p = c4.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single()
q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes)
Assert.False(q.ContainsTypesAccessibleFrom(c4.Assembly))
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.False, q.RawContainsAccessibleTypes)
Assert.False(p.ContainsTypesAccessibleFrom(c4.Assembly))
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.False, p.RawContainsAccessibleTypes)
c4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="C4">
<file name="a.vb">
Namespace P
Namespace Q
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(c3), New VisualBasicCompilationReference(c2)})
p = c4.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single()
q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes)
Assert.Equal(Accessibility.Friend, q.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Friend, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes)
Assert.False(q.ContainsTypesAccessibleFrom(c4.Assembly))
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.False, q.RawContainsAccessibleTypes)
Assert.False(p.ContainsTypesAccessibleFrom(c4.Assembly))
Assert.Equal(ThreeState.False, p.RawContainsAccessibleTypes)
End Sub
<Fact()>
Public Sub Bug4128()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4128">
<file name="a.vb">
Imports A = C.B
Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115
Imports XXXXYYY = UNKNOWN(Of UNKNOWN)
Module X
Class C
End Class
End Module
Module Y
Class C
End Class
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30562: 'C' is ambiguous between declarations in Modules 'X, Y'.
Imports A = C.B
~
BC40056: Namespace or type specified in the Imports 'UNKNOWN.UNKNOWN' 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.
Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'UNKNOWN' is not defined.
Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115
~~~~~~~
BC40056: Namespace or type specified in the Imports 'UNKNOWN' 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.
Imports XXXXYYY = UNKNOWN(Of UNKNOWN)
~~~~~~~~~~~~~~~~~~~
BC30002: Type 'UNKNOWN' is not defined.
Imports XXXXYYY = UNKNOWN(Of UNKNOWN)
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub Bug4220()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4220">
<file name="a.vb">
Imports A
Imports A.B
Imports A.B
Namespace A
Module B
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31051: Namespace or type 'B' has already been imported.
Imports A.B
~~~
</expected>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4220">
<file name="a.vb">
Imports A
Imports A.B
Module Module1
Sub Main()
c()
End Sub
End Module
Namespace A
Module B
Public Sub c()
System.Console.WriteLine("Sub c()")
End Sub
End Module
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
Sub c()
]]>)
End Sub
<Fact()>
Public Sub Bug4180()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug4180">
<file name="a.vb">
Namespace System
Class [Object]
End Class
Class C
Inherits [Object]
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
Assert.Same(compilation.Assembly.GetTypeByMetadataName("System.Object"), compilation.GetTypeByMetadataName("System.C").BaseType)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C1">
<file name="a.vb">
Namespace NS1
Namespace NS2
Public Class C1
End Class
End Namespace
End Namespace
Namespace NS5
Public Module Module3
Public Sub Test()
End Sub
End Module
End Namespace
</file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C2">
<file name="a.vb">
Namespace NS1
Namespace NS2
Namespace C1
Public Class C2
End Class
End Namespace
End Namespace
End Namespace
Namespace NS5
Public Module Module4
Public Sub Test()
End Sub
End Module
End Namespace
</file>
</compilation>)
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace NS1
Module Module1
Sub Main()
Dim x As NS2.C1.C2 = New NS2.C1.C2()
System.Console.WriteLine(x.GetType())
End Sub
End Module
Namespace NS2
Namespace C1
End Namespace
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe)
CompileAndVerify(compilation3, <![CDATA[
NS1.NS2.C1.C2
]]>)
Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C4">
<file name="a.vb">
Namespace NS1
Namespace NS2
Namespace C1
Public Class C3
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>)
compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C3">
<file name="a.vb">
Imports NS1
Module Module1
Sub Main()
Dim x As NS2.C1.C2 = Nothing
End Sub
End Module
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation4)}, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation3,
<expected>
BC30560: 'C1' is ambiguous in the namespace 'NS1.NS2'.
Dim x As NS2.C1.C2 = Nothing
~~~~~~
</expected>)
compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace NS5
Module Module1
Sub Main()
Test()
End Sub
End Module
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation3,
<expected>
BC30562: 'Test' is ambiguous between declarations in Modules 'NS5.Module3, NS5.Module4'.
Test()
~~~~
</expected>)
compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace NS5
Module Module1
Sub Main()
Test()
End Sub
End Module
Module Module2
Sub Test()
System.Console.WriteLine("Module2.Test")
End Sub
End Module
End Namespace </file>
</compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe)
CompileAndVerify(compilation3, <![CDATA[
Module2.Test
]]>)
End Sub
<Fact()>
Public Sub Bug4817()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4817">
<file name="a.vb">
Imports A
Imports B
Class A
Shared Sub Goo()
System.Console.WriteLine("A.Goo()")
End Sub
End Class
Class B
Inherits A
End Class
Module C
Sub Main()
Goo()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
A.Goo()
]]>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4817">
<file name="a.vb">
Imports A
Imports B
Class A
Shared Sub Goo()
System.Console.WriteLine("A.Goo()")
End Sub
End Class
Class B
Inherits A
Overloads Shared Sub Goo(x As Integer)
System.Console.WriteLine("B.Goo()")
End Sub
End Class
Module C
Sub Main()
Goo()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30561: 'Goo' is ambiguous, imported from the namespaces or types 'A, B, A'.
Goo()
~~~
</expected>)
End Sub
<Fact()>
Public Sub LookupOptionMustBeInstance()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Option Explicit On
Interface I
Sub GooInstance()
End Interface
Class A
Public Shared Sub GooShared()
End Sub
Public Sub GooInstance()
End Sub
End Class
Module Module1
Sub Main()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
Dim context = GetContext(compilation, "a.vb", "Sub Main")
Dim globalNS = compilation.GlobalNamespace
Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol)
Dim gooShared = DirectCast(classA.GetMembers("GooShared").Single(), MethodSymbol)
Dim gooInstance = DirectCast(classA.GetMembers("GooInstance").Single(), MethodSymbol)
Dim lr As LookupResult
' Find Shared member
lr = New LookupResult()
context.LookupMember(lr, classA, "GooShared", 0, LookupOptions.MustNotBeInstance, Nothing)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(gooShared, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
lr = New LookupResult()
context.LookupMember(lr, classA, "GooInstance", 0, LookupOptions.MustNotBeInstance, Nothing)
Assert.Equal(LookupResultKind.MustNotBeInstance, lr.Kind)
Assert.True(lr.HasDiagnostic) 'error BC30469: Reference to a non-shared member requires an object reference.
lr = New LookupResult()
context.LookupMember(lr, classA, "GooInstance", 0, LookupOptions.MustBeInstance, Nothing)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(gooInstance, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
lr = New LookupResult()
context.LookupMember(lr, classA, "GooShared", 0, LookupOptions.MustBeInstance, Nothing)
Assert.Equal(LookupResultKind.MustBeInstance, lr.Kind)
Assert.False(lr.HasDiagnostic)
Dim interfaceI = DirectCast(globalNS.GetMembers("I").Single(), NamedTypeSymbol)
Dim ifooInstance = DirectCast(interfaceI.GetMembers("GooInstance").Single(), MethodSymbol)
lr = New LookupResult()
context.LookupMember(lr, interfaceI, "GooInstance", 0, LookupOptions.MustBeInstance, Nothing)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(ifooInstance, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
<WorkItem(545575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545575")>
Public Sub Bug14079()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Interface I
Class Goo
Shared Sub Boo()
End Sub
End Class
End Interface
Class D
Sub Goo()
End Sub
Interface I2
Inherits I
Shadows Class Goo(Of T)
End Class
Class C
Sub Bar()
Goo.Boo()
End Sub
End Class
End Interface
End Class
</file>
</compilation>)
CompilationUtils.AssertNoDiagnostics(compilation)
End Sub
<Fact(), WorkItem(531293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531293")>
Public Sub Bug17900()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4817">
<file name="a.vb">
Imports Undefined
Module Program
Event E
Sub Main()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC40056: Namespace or type specified in the Imports 'Undefined' 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.
Imports Undefined
~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_01()
Dim compilation = CompilationUtils.CreateEmptyCompilation(
<compilation>
<file name="a.vb">
Imports System
Imports System.Windows.Forms
Module Module1
Sub Main()
Dim x As ComponentModel.INotifyPropertyChanged = Nothing 'BIND1:"ComponentModel"
End Sub
End Module
</file>
</compilation>, references:={Net451.mscorlib, Net451.System, Net451.MicrosoftVisualBasic, Net451.SystemWindowsForms})
CompilationUtils.AssertNoDiagnostics(compilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info = semanticModel.GetSymbolInfo(node)
Dim ns = DirectCast(info.Symbol, NamespaceSymbol)
Assert.Equal(NamespaceKind.Module, ns.NamespaceKind)
Assert.Equal("System.ComponentModel", ns.ToTestDisplayString())
Assert.Equal({"System.ComponentModel", "System.Windows.Forms.ComponentModel"},
semanticModel.LookupNamespacesAndTypes(node.Position, name:="ComponentModel").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"System.ComponentModel", "System.Windows.Forms.ComponentModel"},
semanticModel.LookupSymbols(node.Position, name:="ComponentModel").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports Windows.Foundation
Module Module1
Sub Main()
Diagnostics.Debug.WriteLine("") 'BIND1:"Diagnostics"
Dim x = Diagnostics
Diagnostics
End Sub
End Module
</file>
</compilation>, WinRtRefs)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30112: 'Diagnostics' is a namespace and cannot be used as an expression.
Dim x = Diagnostics
~~~~~~~~~~~
BC30112: 'Diagnostics' is a namespace and cannot be used as an expression.
Diagnostics
~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info = semanticModel.GetSymbolInfo(node)
Dim ns = DirectCast(info.Symbol, NamespaceSymbol)
Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind)
Assert.Equal("System.Diagnostics", ns.ToTestDisplayString())
Assert.Equal({"System.Diagnostics", "Windows.Foundation.Diagnostics"},
semanticModel.LookupNamespacesAndTypes(node.Position, name:="Diagnostics").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"System.Diagnostics", "Windows.Foundation.Diagnostics"},
semanticModel.LookupSymbols(node.Position, name:="Diagnostics").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_03()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports NS1
Imports NS2
Module Module1
Sub Main()
NS3. 'BIND1:"NS3"
NS4.T1.M1() 'BIND2:"NS4"
End Sub
End Module
Namespace NS1
Namespace NS3
Namespace NS4
Class T1
Shared Sub M1()
End Sub
End Class
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS3
Namespace NS4
Class T2
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>)
CompilationUtils.AssertNoDiagnostics(compilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Dim info2 = semanticModel.GetSymbolInfo(node2)
Dim ns2 = DirectCast(info2.Symbol, NamespaceSymbol)
Assert.Equal(NamespaceKind.Module, ns2.NamespaceKind)
Assert.Equal("NS1.NS3.NS4", ns2.ToTestDisplayString())
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info1 = semanticModel.GetSymbolInfo(node1)
Dim ns1 = DirectCast(info1.Symbol, NamespaceSymbol)
Assert.Equal(NamespaceKind.Module, ns1.NamespaceKind)
Assert.Equal("NS1.NS3", ns1.ToTestDisplayString())
Assert.Equal({"NS1.NS3", "NS2.NS3"},
semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS3").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS3", "NS2.NS3"},
semanticModel.LookupSymbols(node1.Position, name:="NS3").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_04()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS4
Imports NS5
Imports NS9
Module Module1
Sub Main()
Dim x = GetType(NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
T1) 'BIND3:"T1"
End Sub
Class Test1
Inherits NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
T1 'BIND6:"T1"
End Class
Sub Main2()
Dim x = NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
T1. 'BIND9:"T1"
M1()
End Sub
Sub Main3()
Dim x = GetType(NS6) 'BIND10:"NS6"
Dim y = GetType(NS6. 'BIND11:"NS6"
NS7) 'BIND12:"NS7"
End Sub
Class Test2
Inherits NS6 'BIND13:"NS6"
End Class
Class Test3
Inherits NS6. 'BIND14:"NS6"
NS7 'BIND15:"NS7"
End Class
Sub Main4()
NS6 'BIND16:"NS6"
NS6. 'BIND17:"NS6"
NS7 'BIND18:"NS7"
End Sub
<NS6> 'BIND19:"NS6"
<NS6. 'BIND20:"NS6"
NS7> 'BIND21:"NS7"
<NS6. 'BIND22:"NS6"
NS7. 'BIND23:"NS7"
T1> 'BIND24:"T1"
Class Test4
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS4
Namespace NS6
Namespace NS7
Namespace T1
Class T2
End Class
End Namespace
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'.
Dim x = GetType(NS6. 'BIND1:"NS6"
~~~~~~~~~~~~~~~~~~
BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'.
Inherits NS6. 'BIND4:"NS6"
~~~~~~~~~~~~~~~~~~
BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'.
Dim x = NS6. 'BIND7:"NS6"
~~~~~~~~~~~~~~~~~~
BC30182: Type expected.
Dim x = GetType(NS6) 'BIND10:"NS6"
~~~
BC30182: Type expected.
Dim y = GetType(NS6. 'BIND11:"NS6"
~~~~~~~~~~~~~~~~~~~
BC30182: Type expected.
Inherits NS6 'BIND13:"NS6"
~~~
BC30182: Type expected.
Inherits NS6. 'BIND14:"NS6"
~~~~~~~~~~~~~~~~~~~
BC30112: 'NS6' is a namespace and cannot be used as an expression.
NS6 'BIND16:"NS6"
~~~
BC30112: 'NS6.NS7' is a namespace and cannot be used as an expression.
NS6. 'BIND17:"NS6"
~~~~~~~~~~~~~~~~~~~
BC30182: Type expected.
<NS6> 'BIND19:"NS6"
~~~
BC30182: Type expected.
<NS6. 'BIND20:"NS6"
~~~~~~~~~~~~~~~~~~~
BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'.
<NS6. 'BIND22:"NS6"
~~~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(24) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9, 24}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason)
' Content of this list should determine content of lists below !!!
Assert.Equal({"NS1.NS6.NS7.T1", "NS2.NS6.NS7.T1", "NS4.NS6.NS7.T1", "NS5.NS6.NS7.T1"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {2, 5, 8, 23}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info2.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason)
Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS4.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {1, 4, 7, 22}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info1.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS4.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {10, 13, 16, 19}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info2.Symbol)
Assert.Equal(If(i = 16, CandidateReason.Ambiguous, If(i = 19, CandidateReason.NotAnAttributeType, CandidateReason.NotATypeOrNamespace)), info2.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {12, 15, 18, 21}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(If(i = 18, CandidateReason.Ambiguous, If(i = 21, CandidateReason.NotAnAttributeType, CandidateReason.NotATypeOrNamespace)), info3.CandidateReason)
' Content of this list should determine content of lists below !!!
Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS4.NS6.NS7", "NS5.NS6.NS7", "NS9.NS6.NS7"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {11, 14, 17, 20}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_05()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS4
Imports NS5
Imports NS9
Module Module1
Sub Main()
Dim x = GetType(NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
T1) 'BIND3:"T1"
End Sub
Class Test1
Inherits NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
T1 'BIND6:"T1"
End Class
Sub Main2()
NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
T1. 'BIND9:"T1"
M1()
End Sub
<NS6. 'BIND10:"NS6"
NS7. 'BIND11:"NS7"
T1> 'BIND12:"T1"
Class Test2
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Class T1
Inherits System.Attribute
Shared Sub M1()
End Sub
End Class
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Class T2
End Class
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS4
Namespace NS6
Namespace NS7
Namespace T4
Class T2
End Class
End Namespace
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertNoDiagnostics(compilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(12) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6.NS7.T1", info3.Symbol.ToTestDisplayString())
Next
Dim info12 = semanticModel.GetSymbolInfo(nodes(12))
Assert.Equal("Sub NS1.NS6.NS7.T1..ctor()", info12.Symbol.ToTestDisplayString())
For Each i In {2, 5, 8, 11}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind)
Next
For Each i In {1, 4, 7, 10}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_06()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Sub Main()
Dim x = NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
M1() 'BIND3:"M1"
Dim y = GetType(NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
M1) 'BIND6:"M1"
End Sub
<NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
M1> 'BIND9:"M1"
Class Test1
Inherits NS6. 'BIND10:"NS6"
NS7. 'BIND11:"NS7"
M1 'BIND12:"M1"
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30562: 'M1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.T1, NS2.NS6.NS7.T1, NS5.NS6.NS7.T1'.
Dim x = NS6. 'BIND1:"NS6"
~~~~~~~~~~~~~~~~~~
BC30002: Type 'NS6.NS7.M1' is not defined.
Dim y = GetType(NS6. 'BIND4:"NS6"
~~~~~~~~~~~~~~~~~~
BC30002: Type 'NS6.NS7.M1' is not defined.
<NS6. 'BIND7:"NS6"
~~~~~~~~~~~~~~~~~~
BC30002: Type 'NS6.NS7.M1' is not defined.
Inherits NS6. 'BIND10:"NS6"
~~~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(12) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9, 12}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(If(i = 3, CandidateReason.Ambiguous, CandidateReason.NotATypeOrNamespace), info3.CandidateReason)
' Content of this list should determine content of lists below !!!
Assert.Equal({"Sub NS1.NS6.NS7.T1.M1()", "Sub NS2.NS6.NS7.T1.M1()", "Sub NS5.NS6.NS7.T1.M1()"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {2, 5, 8, 11}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info2.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason)
Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {1, 4, 7, 10}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info1.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_07()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Sub Main()
Dim x = NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
M1() 'BIND3:"M1"
End Sub
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module T1
Sub M1(x as Integer)
End Sub
Sub M1(x as Long)
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'M1' accepts this number of arguments.
M1() 'BIND3:"M1"
~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Dim info3 = semanticModel.GetSymbolInfo(node3)
Assert.Null(info3.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, info3.CandidateReason)
Assert.Equal({"Sub NS1.NS6.NS7.T1.M1(x As System.Int32)", "Sub NS1.NS6.NS7.T1.M1(x As System.Int64)"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Dim info2 = semanticModel.GetSymbolInfo(node2)
Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info1 = semanticModel.GetSymbolInfo(node1)
Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(node1.Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_08()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Sub Main()
NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
M1() 'BIND3:"M1"
End Sub
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>)
CompilationUtils.AssertNoDiagnostics(compilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Dim info3 = semanticModel.GetSymbolInfo(node3)
Assert.Equal("Sub NS1.NS6.NS7.T1.M1()", info3.Symbol.ToTestDisplayString())
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Dim info2 = semanticModel.GetSymbolInfo(node2)
Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info1 = semanticModel.GetSymbolInfo(node1)
Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(node1.Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_09()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Class Test1
Inherits NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
T1 'BIND3:"T1"
End Class
Sub Main()
NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
T1 'BIND6:"T1"
Dim x = GetType(NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
T1) 'BIND9:"T1"
End Sub
<NS6. 'BIND10:"NS6"
NS7. 'BIND11:"NS7"
T1> 'BIND12:"T1"
Class Test2
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module Module1
Class T1
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module Module1
Class T1
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module Module1
Class T1
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module Module1
Class T1
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'.
Inherits NS6. 'BIND1:"NS6"
~~~~~~~~~~~~~~~~~~
BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'.
NS6. 'BIND4:"NS6"
~~~~~~~~~~~~~~~~~~
BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'.
Dim x = GetType(NS6. 'BIND7:"NS6"
~~~~~~~~~~~~~~~~~~
BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'.
<NS6. 'BIND10:"NS6"
~~~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(12) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9, 12}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason)
' Content of this list should determine content of lists below !!!
Assert.Equal({"NS1.NS6.NS7.Module1.T1", "NS2.NS6.NS7.Module1.T1", "NS5.NS6.NS7.Module1.T1"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {2, 5, 8, 11}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info2.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason)
Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {1, 4, 7, 10}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info1.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_10()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Class Test1
Inherits NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
T1 'BIND3:"T1"
End Class
Sub Main()
NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
T1 'BIND6:"T1"
Dim x = GetType(NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
T1) 'BIND9:"T1"
End Sub
<NS6. 'BIND10:"NS6"
NS7. 'BIND11:"NS7"
T1> 'BIND12:"T1"
Class Test2
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module Module1
Class T1
Inherits System.Attribute
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module Module1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module Module1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module Module1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30109: 'Module1.T1' is a class type and cannot be used as an expression.
NS6. 'BIND4:"NS6"
~~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(12) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6.NS7.Module1.T1", info3.Symbol.ToTestDisplayString())
Next
Dim info12 = semanticModel.GetSymbolInfo(nodes(12))
Assert.Equal("Sub NS1.NS6.NS7.Module1.T1..ctor()", info12.Symbol.ToTestDisplayString())
For Each i In {2, 5, 8, 11}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind)
Next
For Each i In {1, 4, 7, 10}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()> <WorkItem(842056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842056")>
Public Sub AmbiguousNamespaces_11()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports A
Imports B
Namespace A.X
Class C
End Class
End Namespace
Namespace B.X
Class C
End Class
End Namespace
Module M
Dim c As X.C
End Module
]]></file>
</compilation>, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37229: 'C' is ambiguous between declarations in namespaces 'A.X, B.X'.
Dim c As X.C
~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants01()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime = DateTime,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
vbCompilation.VerifyDiagnostics() ' no obsolete diagnostic - we select the first one of the given name
CompileAndVerify(vbCompilation, expectedOutput:="2")
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants01b()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime = DateTime,
DATETIME = DateTime,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.Datetime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
vbCompilation.VerifyDiagnostics() ' no obsolete diagnostic - we select the first one of the given name
CompileAndVerify(vbCompilation, expectedOutput:="2")
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
System.Console.WriteLine(CInt(Color.DateTime))
~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02b()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime,
DATETIME,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
System.Console.WriteLine(CInt(Color.DateTime))
~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02c()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime = DateTime,
[System.Obsolete] DATETIME,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
System.Console.WriteLine(CInt(Color.DateTime))
~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02d()
Dim vbCompilation1 = CreateVisualBasicCompilation("VBEnum",
<![CDATA[
Public Enum Color
Red
Green
DateTime
<System.Obsolete> Datetime = DateTime
DATETIME
Blue
End Enum
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
CompilationUtils.AssertTheseDiagnostics(vbCompilation1,
<expected><![CDATA[
BC31421: 'Datetime' is already declared in this enum.
<System.Obsolete> Datetime = DateTime
~~~~~~~~
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
<System.Obsolete> Datetime = DateTime
~~~~~~~~
BC31421: 'DATETIME' is already declared in this enum.
DATETIME
~~~~~~~~
]]></expected>)
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedAssemblies:={New VisualBasicCompilationReference(vbCompilation1), MscorlibRef, MsvbRef})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
System.Console.WriteLine(CInt(Color.DateTime))
~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02e()
Dim vbCompilation1 = CreateVisualBasicCompilation("VBEnum",
<![CDATA[
Public Enum Color
Red
Green
DateTime
<System.Obsolete> Datetime = 2
Blue
End Enum
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
CompilationUtils.AssertTheseDiagnostics(vbCompilation1,
<expected><![CDATA[
BC31421: 'Datetime' is already declared in this enum.
<System.Obsolete> Datetime = 2
~~~~~~~~
]]></expected>)
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedAssemblies:={New VisualBasicCompilationReference(vbCompilation1), MscorlibRef, MsvbRef})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
]]></expected>)
CompileAndVerify(vbCompilation, expectedOutput:="2")
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.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class LookupTests
Inherits BasicTestBase
Private Function GetContext(compilation As VisualBasicCompilation,
treeName As String,
textToFind As String) As Binder
Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName)
Dim position = CompilationUtils.FindPositionFromText(tree, textToFind)
Return DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel).GetEnclosingBinder(position)
End Function
<Fact()>
Public Sub TestLookupResult()
Dim sym1 = New MockAssemblySymbol("hello") ' just a symbol to put in results
Dim sym2 = New MockAssemblySymbol("goodbye") ' just a symbol to put in results
Dim sym3 = New MockAssemblySymbol("world") ' just a symbol to put in results
Dim sym4 = New MockAssemblySymbol("banana") ' just a symbol to put in results
Dim sym5 = New MockAssemblySymbol("apple") ' just a symbol to put in results
Dim meth1 = New MockMethodSymbol("goo") ' just a symbol to put in results
Dim meth2 = New MockMethodSymbol("bag") ' just a symbol to put in results
Dim meth3 = New MockMethodSymbol("baz") ' just a symbol to put in results
Dim r1 = New LookupResult()
r1.SetFrom(SingleLookupResult.Empty)
Assert.False(r1.HasSymbol)
Assert.False(r1.IsGood)
Assert.False(r1.HasDiagnostic)
Assert.False(r1.StopFurtherLookup)
Dim r2 = SingleLookupResult.Good(sym1)
Dim _r2 = New LookupResult()
_r2.SetFrom(r2)
Assert.True(_r2.HasSymbol)
Assert.True(_r2.IsGood)
Assert.Same(sym1, _r2.SingleSymbol)
Assert.False(_r2.HasDiagnostic)
Assert.True(_r2.StopFurtherLookup)
Dim r3 = New LookupResult()
r3.SetFrom(SingleLookupResult.Ambiguous(ImmutableArray.Create(Of Symbol)(sym1, sym2, sym3), AddressOf GenerateAmbiguity))
Assert.True(r3.HasSymbol)
Assert.False(r3.IsGood)
Assert.Same(sym1, r3.SingleSymbol)
Assert.True(r3.HasDiagnostic)
Assert.True(r3.StopFurtherLookup)
Dim diag3 = DirectCast(r3.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Same(sym1, diag3.AmbiguousSymbols.Item(0))
Assert.Same(sym2, diag3.AmbiguousSymbols.Item(1))
Assert.Same(sym3, diag3.AmbiguousSymbols.Item(2))
Dim r4 = New LookupResult()
r4.SetFrom(SingleLookupResult.Inaccessible(sym2, New BadSymbolDiagnostic(sym2, ERRID.ERR_InaccessibleSymbol2, sym2)))
Assert.True(r4.HasSymbol)
Assert.False(r4.IsGood)
Assert.Same(sym2, r4.SingleSymbol)
Assert.True(r4.HasDiagnostic)
Assert.False(r4.StopFurtherLookup)
Dim diag4 = DirectCast(r4.Diagnostic, BadSymbolDiagnostic)
Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag4.Code)
Assert.Same(sym2, diag4.BadSymbol)
Dim r5 = New LookupResult()
r5.SetFrom(SingleLookupResult.WrongArity(sym3, ERRID.ERR_IndexedNotArrayOrProc))
Assert.True(r5.HasSymbol)
Assert.False(r5.IsGood)
Assert.Same(sym3, r5.SingleSymbol)
Assert.True(r5.HasDiagnostic)
Assert.False(r5.StopFurtherLookup)
Dim diag5 = r5.Diagnostic
Assert.Equal(ERRID.ERR_IndexedNotArrayOrProc, diag5.Code)
Dim r6 = New LookupResult()
r6.MergePrioritized(r1)
r6.MergePrioritized(r2)
Assert.True(r6.HasSymbol)
Assert.Same(sym1, r6.SingleSymbol)
Assert.False(r6.HasDiagnostic)
Assert.True(r6.StopFurtherLookup)
r6.Free()
Dim r7 = New LookupResult()
r7.MergePrioritized(r2)
r7.MergePrioritized(r1)
Assert.True(r7.HasSymbol)
Assert.Same(sym1, r7.SingleSymbol)
Assert.False(r7.HasDiagnostic)
Assert.True(r7.StopFurtherLookup)
Dim r8 = New LookupResult()
r8.SetFrom(SingleLookupResult.Good(sym4))
Dim r9 = New LookupResult()
r9.SetFrom(r2)
r9.MergePrioritized(r8)
Assert.True(r9.HasSymbol)
Assert.Same(sym1, r9.SingleSymbol)
Assert.False(r9.HasDiagnostic)
Assert.True(r9.StopFurtherLookup)
Dim r10 = New LookupResult()
r10.SetFrom(r3)
r10.MergePrioritized(r8)
r10.MergePrioritized(r2)
Assert.True(r10.HasSymbol)
Assert.Same(sym1, r10.SingleSymbol)
Assert.True(r10.HasDiagnostic)
Assert.True(r10.StopFurtherLookup)
Dim diag10 = DirectCast(r10.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Same(sym1, diag10.AmbiguousSymbols.Item(0))
Assert.Same(sym2, diag10.AmbiguousSymbols.Item(1))
Assert.Same(sym3, diag10.AmbiguousSymbols.Item(2))
Dim r11 = New LookupResult()
r11.MergePrioritized(r1)
r11.MergePrioritized(r5)
r11.MergePrioritized(r3)
r11.MergePrioritized(r8)
r11.MergePrioritized(r2)
Assert.True(r11.HasSymbol)
Assert.Same(sym1, r11.SingleSymbol)
Assert.True(r11.HasDiagnostic)
Assert.True(r11.StopFurtherLookup)
Dim diag11 = DirectCast(r11.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Same(sym1, diag11.AmbiguousSymbols.Item(0))
Assert.Same(sym2, diag11.AmbiguousSymbols.Item(1))
Assert.Same(sym3, diag11.AmbiguousSymbols.Item(2))
Dim r12 = New LookupResult()
Dim r12Empty = New LookupResult()
r12.MergePrioritized(r1)
r12.MergePrioritized(r12Empty)
Assert.False(r12.HasSymbol)
Assert.False(r12.HasDiagnostic)
Assert.False(r12.StopFurtherLookup)
Dim r13 = New LookupResult()
r13.MergePrioritized(r1)
r13.MergePrioritized(r5)
r13.MergePrioritized(r4)
Assert.True(r13.HasSymbol)
Assert.Same(sym2, r13.SingleSymbol)
Assert.True(r13.HasDiagnostic)
Assert.False(r13.StopFurtherLookup)
Dim diag13 = DirectCast(r13.Diagnostic, BadSymbolDiagnostic)
Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag13.Code)
Assert.Same(sym2, diag13.BadSymbol)
Dim r14 = New LookupResult()
r14.MergeAmbiguous(r1, AddressOf GenerateAmbiguity)
r14.MergeAmbiguous(r5, AddressOf GenerateAmbiguity)
r14.MergeAmbiguous(r4, AddressOf GenerateAmbiguity)
Assert.True(r14.HasSymbol)
Assert.Same(sym2, r14.SingleSymbol)
Assert.True(r14.HasDiagnostic)
Assert.False(r14.StopFurtherLookup)
Dim diag14 = DirectCast(r14.Diagnostic, BadSymbolDiagnostic)
Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag14.Code)
Assert.Same(sym2, diag14.BadSymbol)
Dim r15 = New LookupResult()
r15.MergeAmbiguous(r1, AddressOf GenerateAmbiguity)
r15.MergeAmbiguous(r8, AddressOf GenerateAmbiguity)
r15.MergeAmbiguous(r3, AddressOf GenerateAmbiguity)
r15.MergeAmbiguous(r14, AddressOf GenerateAmbiguity)
Assert.True(r15.HasSymbol)
Assert.Same(sym4, r15.SingleSymbol)
Assert.True(r15.HasDiagnostic)
Assert.True(r15.StopFurtherLookup)
Dim diag15 = DirectCast(r15.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Same(sym4, diag15.AmbiguousSymbols.Item(0))
Assert.Same(sym1, diag15.AmbiguousSymbols.Item(1))
Assert.Same(sym2, diag15.AmbiguousSymbols.Item(2))
Assert.Same(sym3, diag15.AmbiguousSymbols.Item(3))
Dim r16 = SingleLookupResult.Good(meth1)
Dim r17 = SingleLookupResult.Good(meth2)
Dim r18 = SingleLookupResult.Good(meth3)
Dim r19 = New LookupResult()
r19.MergeMembersOfTheSameType(r16, False)
Assert.True(r19.StopFurtherLookup)
Assert.Equal(1, r19.Symbols.Count)
Assert.False(r19.HasDiagnostic)
r19.MergeMembersOfTheSameType(r17, False)
Assert.True(r19.StopFurtherLookup)
Assert.Equal(2, r19.Symbols.Count)
Assert.False(r19.HasDiagnostic)
r19.MergeMembersOfTheSameType(r18, False)
Assert.True(r19.StopFurtherLookup)
Assert.Equal(3, r19.Symbols.Count)
Assert.Equal(r16.Symbol, r19.Symbols(0))
Assert.Equal(r17.Symbol, r19.Symbols(1))
Assert.Equal(r18.Symbol, r19.Symbols(2))
Assert.False(r19.HasDiagnostic)
r19.MergeAmbiguous(r2, AddressOf GenerateAmbiguity)
Assert.True(r19.StopFurtherLookup)
Assert.Equal(1, r19.Symbols.Count)
Assert.Equal(r16.Symbol, r19.SingleSymbol)
Assert.True(r19.HasDiagnostic)
Dim diag19 = DirectCast(r19.Diagnostic, AmbiguousSymbolDiagnostic)
Assert.Equal(4, diag19.AmbiguousSymbols.Length)
Assert.Equal(r16.Symbol, diag19.AmbiguousSymbols(0))
Assert.Equal(r17.Symbol, diag19.AmbiguousSymbols(1))
Assert.Equal(r18.Symbol, diag19.AmbiguousSymbols(2))
Assert.Equal(r2.Symbol, diag19.AmbiguousSymbols(3))
End Sub
Private Function GenerateAmbiguity(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic
Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInModules2, syms, New FormattedSymbolList(syms.AsEnumerable))
End Function
<Fact()>
Public Sub MemberLookup1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Comp">
<file name="a.vb">
Option Strict On
Option Explicit On
Class A
Public Class M3(Of T)
End Class
Public Overloads Sub M4(ByVal x As Integer, ByVal y As Integer)
End Sub
Public Overloads Sub M5(ByVal x As Integer, ByVal y As Integer)
End Sub
End Class
Class B
Inherits A
Public Shared Sub M1(Of T)()
End Sub
Public Shared Sub M2()
End Sub
Public Shadows M3 As Integer
Public Overloads Sub M4(ByVal x As Integer, ByVal y As String)
End Sub
Public Shadows Sub M5(ByVal x As Integer, ByVal y As String)
End Sub
End Class
Class C
Inherits B
Public Shadows Class M1
End Class
Public Shadows Class M2(Of T)
End Class
Public Overloads Sub M4()
End Sub
Public Overloads Sub M4(ByVal x As Integer)
End Sub
Public Overloads Sub M5()
End Sub
Public Overloads Sub M5(ByVal x As Integer)
End Sub
End Class
Module Module1
Sub Main()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
Dim context = GetContext(compilation, "a.vb", "Sub Main")
Dim globalNS = compilation.GlobalNamespace
Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol)
Dim classB = DirectCast(globalNS.GetMembers("B").Single(), NamedTypeSymbol)
Dim classC = DirectCast(globalNS.GetMembers("C").Single(), NamedTypeSymbol)
Dim classA_M3 = DirectCast(classA.GetMembers("M3").Single(), NamedTypeSymbol)
Dim methA_M4 = DirectCast(classA.GetMembers("M4").Single(), MethodSymbol)
Dim methA_M5 = DirectCast(classA.GetMembers("M5").Single(), MethodSymbol)
Dim methB_M1 = DirectCast(classB.GetMembers("M1").Single(), MethodSymbol)
Dim methB_M2 = DirectCast(classB.GetMembers("M2").Single(), MethodSymbol)
Dim methB_M4 = DirectCast(classB.GetMembers("M4").Single(), MethodSymbol)
Dim methB_M5 = DirectCast(classB.GetMembers("M5").Single(), MethodSymbol)
Dim fieldB_M3 = DirectCast(classB.GetMembers("M3").Single(), FieldSymbol)
Dim classC_M1 = DirectCast(classC.GetMembers("M1").Single(), NamedTypeSymbol)
Dim classC_M2 = DirectCast(classC.GetMembers("M2").Single(), NamedTypeSymbol)
Dim methC_M4_0 = DirectCast(classC.GetMembers("M4")(0), MethodSymbol)
Dim methC_M4_1 = DirectCast(classC.GetMembers("M4")(1), MethodSymbol)
Dim methC_M5_0 = DirectCast(classC.GetMembers("M5")(0), MethodSymbol)
Dim methC_M5_1 = DirectCast(classC.GetMembers("M5")(1), MethodSymbol)
Dim lr As LookupResult
' nothing found
lr = New LookupResult()
context.LookupMember(lr, classC, "fizzle", 0, Nothing, Nothing)
Assert.Equal(LookupResultKind.Empty, lr.Kind)
' non-generic class shadows with arity 0
lr = New LookupResult()
context.LookupMember(lr, classC, "M1", 0, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(classC_M1, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
' method found with arity 1
lr = New LookupResult()
context.LookupMember(lr, classC, "M1", 1, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(methB_M1, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
' generic class shadows with arity 1
lr = New LookupResult()
context.LookupMember(lr, classC, "M2", 1, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(classC_M2, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
' method found with arity 0
lr = New LookupResult()
context.LookupMember(lr, classC, "M2", 0, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(methB_M2, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
' field shadows with arity 1
lr = New LookupResult()
context.LookupMember(lr, classC, "M3", 1, Nothing, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(fieldB_M3, lr.Symbols.Single())
Assert.True(lr.HasDiagnostic)
' should collection all overloads of M4
lr = New LookupResult()
context.LookupMember(lr, classC, "M4", 1, LookupOptions.AllMethodsOfAnyArity, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(4, lr.Symbols.Count)
Assert.Contains(methA_M4, lr.Symbols)
Assert.Contains(methB_M4, lr.Symbols)
Assert.Contains(methC_M4_0, lr.Symbols)
Assert.Contains(methC_M4_1, lr.Symbols)
Assert.False(lr.HasDiagnostic)
' shouldn't get A.M5 because B.M5 is marked Shadows
lr = New LookupResult()
context.LookupMember(lr, classC, "M5", 1, LookupOptions.AllMethodsOfAnyArity, Nothing)
Assert.True(lr.StopFurtherLookup)
Assert.Equal(3, lr.Symbols.Count)
Assert.DoesNotContain(methA_M5, lr.Symbols)
Assert.Contains(methB_M5, lr.Symbols)
Assert.Contains(methC_M5_0, lr.Symbols)
Assert.Contains(methC_M5_1, lr.Symbols)
Assert.False(lr.HasDiagnostic)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact()>
Public Sub Bug3024()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug3024">
<file name="a.vb">
Imports P
Imports R
Module C
Dim x As Q
End Module
Namespace R
Module M
Class Q
End Class
End Module
End Namespace
Namespace P.Q
End Namespace
</file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
Assert.Same(compilation.GetTypeByMetadataName("R.M+Q"), compilation.GetTypeByMetadataName("C").GetMembers("x").OfType(Of FieldSymbol)().Single().Type)
End Sub
<Fact()>
Public Sub Bug3025()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug3025">
<file name="a.vb">
Imports P
Imports R
Module C
Dim x As Q
End Module
Namespace R
Module M
Class Q
End Class
End Module
End Namespace
Namespace P.Q
Class Z
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30182: Type expected.
Dim x As Q
~
</expected>)
End Sub
<Fact()>
Public Sub Bug4099()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4099">
<file name="a.vb">
Imports N
Imports K
Namespace N
Module M
Class C
End Class
End Module
End Namespace
Namespace K
Class C
End Class
End Namespace
Class A
Inherits C
End Class
</file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
Assert.Same(compilation.GetTypeByMetadataName("K.C"), compilation.GetTypeByMetadataName("A").BaseType)
End Sub
<Fact()>
Public Sub Bug4100()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug4100">
<file name="a.vb">
Imports N
Imports K
Namespace N
Class C
End Class
End Namespace
Namespace K
Namespace C
Class D
End Class
End Namespace
End Namespace
Class A
Inherits C
End Class
</file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
Assert.Same(compilation.GetTypeByMetadataName("N.C"), compilation.GetTypeByMetadataName("A").BaseType)
compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug4100">
<file name="a.vb">
Imports K
Imports N
Namespace N
Class C
End Class
End Namespace
Namespace K
Namespace C
Class D
End Class
End Namespace
End Namespace
Class A
Inherits C
End Class
</file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
Assert.Same(compilation.GetTypeByMetadataName("N.C"), compilation.GetTypeByMetadataName("A").BaseType)
End Sub
<Fact()>
Public Sub Bug3015()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug3015">
<file name="a.vb">
Imports P
Imports R
Module Module1
Sub Main()
Dim x As Q = New Q()
System.Console.WriteLine(x.GetType())
End Sub
End Module
Namespace R
Class Q
End Class
End Namespace
Namespace P.Q
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
R.Q
]]>)
End Sub
<Fact()>
Public Sub Bug3014()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug3014">
<file name="a.vb">
Imports P = System
Imports R
Module C
Sub Main()
Dim x As P(Of Integer)
x=Nothing
End Sub
End Module
Namespace R
Class P(Of T)
End Class
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32045: 'System' has no type parameters and so cannot have type arguments.
Dim x As P(Of Integer)
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AmbiguityInImports()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguityInImports1">
<file name="a.vb">
Namespace NS1
Friend Class CT1
End Class
Friend Class CT2
End Class
Public Class CT3(Of T)
End Class
Public Class CT4
End Class
Public Module M1
Friend Class CT1
End Class
Public Class CT2(Of T)
End Class
Public Class CT3
End Class
End Module
Public Module M2
Public Class CT3
End Class
End Module
End Namespace
Namespace NS2
Public Class CT5
End Class
Public Module M3
Public Class CT5
End Class
End Module
End Namespace
Namespace NS3
Public Class CT5
End Class
End Namespace
</file>
</compilation>)
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguityInImports3">
<file name="a.vb">
Namespace NS1
Namespace CT4
End Namespace
End Namespace
Namespace NS2
Namespace CT5
End Namespace
End Namespace
</file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="AmbiguityInImports2">
<file name="a.vb">
Imports NS2
Imports NS3
Namespace NS1
Module Module1
Sub Test()
Dim x1 As CT1
Dim x2 As CT2
Dim x3 As CT3
Dim x4 As CT4
Dim x5 As CT5
x1 = Nothing
x2 = Nothing
x3 = Nothing
x4 = Nothing
x5 = Nothing
End Sub
End Module
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1),
New VisualBasicCompilationReference(compilation3)})
CompilationUtils.AssertTheseDiagnostics(compilation2,
<expected>
BC30389: 'NS1.CT1' is not accessible in this context because it is 'Friend'.
Dim x1 As CT1
~~~
BC30389: 'NS1.CT2' is not accessible in this context because it is 'Friend'.
Dim x2 As CT2
~~~
BC30562: 'CT3' is ambiguous between declarations in Modules 'NS1.M1, NS1.M2'.
Dim x3 As CT3
~~~
BC30560: 'CT4' is ambiguous in the namespace 'NS1'.
Dim x4 As CT4
~~~
BC30560: 'CT5' is ambiguous in the namespace 'NS2'.
Dim x5 As CT5
~~~
</expected>)
End Sub
<Fact()>
Public Sub TieBreakingInImports()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TieBreakingInImports1">
<file name="a.vb">
Namespace NS1
Namespace Test1
Public Class Test3
End Class
End Namespace
Public Class Test2
End Class
Public Class Test5
End Class
End Namespace
Namespace NS2
Namespace Test1
Public Class Test4
End Class
End Namespace
Public Class Test5
End Class
End Namespace
</file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TieBreakingInImports2">
<file name="a.vb">
Namespace NS3
Class Test1
End Class
Class Test1(Of T)
End Class
Class Test5
End Class
End Namespace
</file>
</compilation>)
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TieBreakingInImports3">
<file name="a.vb">
Namespace NS2
Class Test2(Of T)
End Class
End Namespace
</file>
</compilation>)
Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="TieBreakingInImports4">
<file name="a.vb">
Imports NS1
Imports NS2
Imports NS3
Module Test
Sub Test()
Dim x1 As Test1 = Nothing
Dim x2 As Test1(Of Integer) = Nothing
Dim x3 As Test2(Of Integer) = Nothing
Dim x4 As Test5 = Nothing
End Sub
End Module
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1),
New VisualBasicCompilationReference(compilation2),
New VisualBasicCompilationReference(compilation3)})
CompilationUtils.AssertTheseDiagnostics(compilation4,
<expected>
BC30182: Type expected.
Dim x1 As Test1 = Nothing
~~~~~
BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'.
Dim x2 As Test1(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'.
Dim x3 As Test2(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS1, NS2'.
Dim x4 As Test5 = Nothing
~~~~~
</expected>)
Dim compilation5 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="TieBreakingInImports4">
<file name="a.vb">
Imports NS2
Imports NS3
Imports NS1
Module Test
Sub Test()
Dim x1 As Test1 = Nothing
Dim x2 As Test1(Of Integer) = Nothing
Dim x3 As Test2(Of Integer) = Nothing
Dim x4 As Test5 = Nothing
End Sub
End Module
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1),
New VisualBasicCompilationReference(compilation2),
New VisualBasicCompilationReference(compilation3)})
CompilationUtils.AssertTheseDiagnostics(compilation5,
<expected>
BC30182: Type expected.
Dim x1 As Test1 = Nothing
~~~~~
BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'.
Dim x2 As Test1(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'.
Dim x3 As Test2(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS2, NS1'.
Dim x4 As Test5 = Nothing
~~~~~
</expected>)
Dim compilation6 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="TieBreakingInImports4">
<file name="a.vb">
Imports NS3
Imports NS1
Imports NS2
Module Test
Sub Test()
Dim x1 As Test1 = Nothing
Dim x2 As Test1(Of Integer) = Nothing
Dim x3 As Test2(Of Integer) = Nothing
Dim x4 As Test5 = Nothing
End Sub
End Module
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1),
New VisualBasicCompilationReference(compilation2),
New VisualBasicCompilationReference(compilation3)})
CompilationUtils.AssertTheseDiagnostics(compilation6,
<expected>
BC30182: Type expected.
Dim x1 As Test1 = Nothing
~~~~~
BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'.
Dim x2 As Test1(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'.
Dim x3 As Test2(Of Integer) = Nothing
~~~~~~~~~~~~~~~~~
BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS1, NS2'.
Dim x4 As Test5 = Nothing
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RecursiveCheckForAccessibleTypesWithinANamespace()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RecursiveCheckForAccessibleTypesWithinANamespace1">
<file name="a.vb">
Imports P
Module Module1
Sub Main()
Dim x As Q.R.S = New Q.R.S()
System.Console.WriteLine(x.GetType())
End Sub
End Module
Namespace P
Namespace Q
Namespace R
Public Class S
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
P.Q.R.S
]]>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RecursiveCheckForAccessibleTypesWithinANamespace2">
<file name="a.vb">
Imports P
Module Module1
Sub Main()
Dim x As Q.R.S = New Q.R.S()
System.Console.WriteLine(x.GetType())
End Sub
End Module
Namespace P
Namespace Q
Namespace R
Friend Class S
End Class
Friend Class T
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
P.Q.R.S
]]>)
End Sub
<Fact()>
Public Sub DoNotLoadTypesForAccessibilityOfMostAccessibleTypeWithinANamespace()
' We need to be careful about metadata references we use here.
' The test checks that fields of namespace symbols are initialized in certain order.
' If we used a shared Mscorlib reference then other tests might have already initialized it's shared AssemblySymbol.
Dim nonSharedMscorlibReference = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display:="mscorlib.v4_0_30319.dll")
Dim c = VisualBasicCompilation.Create("DoNotLoadTypesForAccessibilityOfMostAccessibleTypeWithinANamespace",
syntaxTrees:={Parse(<text>
Namespace P
End Namespace
</text>.Value)},
references:={nonSharedMscorlibReference})
Dim system = c.Assembly.Modules(0).GetReferencedAssemblySymbols()(0).GlobalNamespace.GetMembers("System").OfType(Of PENamespaceSymbol)().Single()
Dim deployment = system.GetMembers("Deployment").OfType(Of PENamespaceSymbol)().Single()
Dim internal = deployment.GetMembers("Internal").OfType(Of PENamespaceSymbol)().Single()
Dim isolation = internal.GetMembers("Isolation").OfType(Of PENamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, deployment.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, internal.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, isolation.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.False(isolation.AreTypesLoaded)
Assert.Equal(Accessibility.Friend, isolation.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.False(isolation.AreTypesLoaded)
Assert.Equal(Accessibility.Friend, isolation.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, deployment.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, internal.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
isolation.GetTypeMembers()
Assert.True(isolation.AreTypesLoaded)
Dim io = system.GetMembers("IO").OfType(Of PENamespaceSymbol)().Single()
Dim isolatedStorage = io.GetMembers("IsolatedStorage").OfType(Of PENamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, io.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, isolatedStorage.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.False(isolatedStorage.AreTypesLoaded)
Assert.Equal(Accessibility.Public, isolatedStorage.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.False(isolatedStorage.AreTypesLoaded)
Assert.Equal(Accessibility.Public, isolatedStorage.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Public, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Public, io.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
End Sub
<Fact()>
Public Sub TestMergedNamespaceContainsTypesAccessibleFrom()
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C1">
<file name="a.vb">
Namespace P
Namespace Q
Public Class R
End Class
End Namespace
End Namespace
</file>
</compilation>)
Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C2">
<file name="a.vb">
Namespace P
Namespace Q
Friend Class S
End Class
End Namespace
End Namespace
</file>
</compilation>)
Dim c3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace P
Namespace Q
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(c1), New VisualBasicCompilationReference(c2)})
Dim p = c3.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single()
Dim q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(0, p.RawContainsAccessibleTypes)
Assert.Equal(0, q.RawContainsAccessibleTypes)
Assert.Equal(Accessibility.Public, q.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Public, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Public, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(0, p.RawContainsAccessibleTypes)
Assert.Equal(0, q.RawContainsAccessibleTypes)
Assert.True(q.ContainsTypesAccessibleFrom(c3.Assembly))
Assert.True(p.ContainsTypesAccessibleFrom(c3.Assembly))
Assert.Equal(0, p.RawContainsAccessibleTypes)
Assert.Equal(0, q.RawContainsAccessibleTypes)
c3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace P
Namespace Q
Friend Class U
End Class
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(c2)})
p = c3.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single()
q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes)
Assert.True(q.ContainsTypesAccessibleFrom(c3.Assembly))
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.True, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.True, q.RawContainsAccessibleTypes)
Assert.True(p.ContainsTypesAccessibleFrom(c3.Assembly))
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Dim c4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="C4">
<file name="a.vb">
Namespace P
Namespace Q
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(c3), New VisualBasicCompilationReference(c2)})
p = c4.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single()
q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes)
Assert.False(q.ContainsTypesAccessibleFrom(c4.Assembly))
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.False, q.RawContainsAccessibleTypes)
Assert.False(p.ContainsTypesAccessibleFrom(c4.Assembly))
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.False, p.RawContainsAccessibleTypes)
c4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="C4">
<file name="a.vb">
Namespace P
Namespace Q
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(c3), New VisualBasicCompilationReference(c2)})
p = c4.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single()
q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single()
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes)
Assert.Equal(Accessibility.Friend, q.DeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(Accessibility.Friend, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType)
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes)
Assert.False(q.ContainsTypesAccessibleFrom(c4.Assembly))
Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes)
Assert.Equal(ThreeState.False, q.RawContainsAccessibleTypes)
Assert.False(p.ContainsTypesAccessibleFrom(c4.Assembly))
Assert.Equal(ThreeState.False, p.RawContainsAccessibleTypes)
End Sub
<Fact()>
Public Sub Bug4128()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4128">
<file name="a.vb">
Imports A = C.B
Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115
Imports XXXXYYY = UNKNOWN(Of UNKNOWN)
Module X
Class C
End Class
End Module
Module Y
Class C
End Class
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30562: 'C' is ambiguous between declarations in Modules 'X, Y'.
Imports A = C.B
~
BC40056: Namespace or type specified in the Imports 'UNKNOWN.UNKNOWN' 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.
Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'UNKNOWN' is not defined.
Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115
~~~~~~~
BC40056: Namespace or type specified in the Imports 'UNKNOWN' 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.
Imports XXXXYYY = UNKNOWN(Of UNKNOWN)
~~~~~~~~~~~~~~~~~~~
BC30002: Type 'UNKNOWN' is not defined.
Imports XXXXYYY = UNKNOWN(Of UNKNOWN)
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub Bug4220()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4220">
<file name="a.vb">
Imports A
Imports A.B
Imports A.B
Namespace A
Module B
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31051: Namespace or type 'B' has already been imported.
Imports A.B
~~~
</expected>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4220">
<file name="a.vb">
Imports A
Imports A.B
Module Module1
Sub Main()
c()
End Sub
End Module
Namespace A
Module B
Public Sub c()
System.Console.WriteLine("Sub c()")
End Sub
End Module
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
Sub c()
]]>)
End Sub
<Fact()>
Public Sub Bug4180()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug4180">
<file name="a.vb">
Namespace System
Class [Object]
End Class
Class C
Inherits [Object]
End Class
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
Assert.Same(compilation.Assembly.GetTypeByMetadataName("System.Object"), compilation.GetTypeByMetadataName("System.C").BaseType)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C1">
<file name="a.vb">
Namespace NS1
Namespace NS2
Public Class C1
End Class
End Namespace
End Namespace
Namespace NS5
Public Module Module3
Public Sub Test()
End Sub
End Module
End Namespace
</file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="C2">
<file name="a.vb">
Namespace NS1
Namespace NS2
Namespace C1
Public Class C2
End Class
End Namespace
End Namespace
End Namespace
Namespace NS5
Public Module Module4
Public Sub Test()
End Sub
End Module
End Namespace
</file>
</compilation>)
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace NS1
Module Module1
Sub Main()
Dim x As NS2.C1.C2 = New NS2.C1.C2()
System.Console.WriteLine(x.GetType())
End Sub
End Module
Namespace NS2
Namespace C1
End Namespace
End Namespace
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe)
CompileAndVerify(compilation3, <![CDATA[
NS1.NS2.C1.C2
]]>)
Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="C4">
<file name="a.vb">
Namespace NS1
Namespace NS2
Namespace C1
Public Class C3
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>)
compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C3">
<file name="a.vb">
Imports NS1
Module Module1
Sub Main()
Dim x As NS2.C1.C2 = Nothing
End Sub
End Module
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation4)}, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation3,
<expected>
BC30560: 'C1' is ambiguous in the namespace 'NS1.NS2'.
Dim x As NS2.C1.C2 = Nothing
~~~~~~
</expected>)
compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace NS5
Module Module1
Sub Main()
Test()
End Sub
End Module
End Namespace
</file>
</compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation3,
<expected>
BC30562: 'Test' is ambiguous between declarations in Modules 'NS5.Module3, NS5.Module4'.
Test()
~~~~
</expected>)
compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="C3">
<file name="a.vb">
Namespace NS5
Module Module1
Sub Main()
Test()
End Sub
End Module
Module Module2
Sub Test()
System.Console.WriteLine("Module2.Test")
End Sub
End Module
End Namespace </file>
</compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe)
CompileAndVerify(compilation3, <![CDATA[
Module2.Test
]]>)
End Sub
<Fact()>
Public Sub Bug4817()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4817">
<file name="a.vb">
Imports A
Imports B
Class A
Shared Sub Goo()
System.Console.WriteLine("A.Goo()")
End Sub
End Class
Class B
Inherits A
End Class
Module C
Sub Main()
Goo()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
A.Goo()
]]>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4817">
<file name="a.vb">
Imports A
Imports B
Class A
Shared Sub Goo()
System.Console.WriteLine("A.Goo()")
End Sub
End Class
Class B
Inherits A
Overloads Shared Sub Goo(x As Integer)
System.Console.WriteLine("B.Goo()")
End Sub
End Class
Module C
Sub Main()
Goo()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30561: 'Goo' is ambiguous, imported from the namespaces or types 'A, B, A'.
Goo()
~~~
</expected>)
End Sub
<Fact()>
Public Sub LookupOptionMustBeInstance()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Option Explicit On
Interface I
Sub GooInstance()
End Interface
Class A
Public Shared Sub GooShared()
End Sub
Public Sub GooInstance()
End Sub
End Class
Module Module1
Sub Main()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
Dim context = GetContext(compilation, "a.vb", "Sub Main")
Dim globalNS = compilation.GlobalNamespace
Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol)
Dim gooShared = DirectCast(classA.GetMembers("GooShared").Single(), MethodSymbol)
Dim gooInstance = DirectCast(classA.GetMembers("GooInstance").Single(), MethodSymbol)
Dim lr As LookupResult
' Find Shared member
lr = New LookupResult()
context.LookupMember(lr, classA, "GooShared", 0, LookupOptions.MustNotBeInstance, Nothing)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(gooShared, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
lr = New LookupResult()
context.LookupMember(lr, classA, "GooInstance", 0, LookupOptions.MustNotBeInstance, Nothing)
Assert.Equal(LookupResultKind.MustNotBeInstance, lr.Kind)
Assert.True(lr.HasDiagnostic) 'error BC30469: Reference to a non-shared member requires an object reference.
lr = New LookupResult()
context.LookupMember(lr, classA, "GooInstance", 0, LookupOptions.MustBeInstance, Nothing)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(gooInstance, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
lr = New LookupResult()
context.LookupMember(lr, classA, "GooShared", 0, LookupOptions.MustBeInstance, Nothing)
Assert.Equal(LookupResultKind.MustBeInstance, lr.Kind)
Assert.False(lr.HasDiagnostic)
Dim interfaceI = DirectCast(globalNS.GetMembers("I").Single(), NamedTypeSymbol)
Dim ifooInstance = DirectCast(interfaceI.GetMembers("GooInstance").Single(), MethodSymbol)
lr = New LookupResult()
context.LookupMember(lr, interfaceI, "GooInstance", 0, LookupOptions.MustBeInstance, Nothing)
Assert.Equal(1, lr.Symbols.Count)
Assert.Equal(ifooInstance, lr.Symbols.Single())
Assert.False(lr.HasDiagnostic)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
End Sub
<Fact>
<WorkItem(545575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545575")>
Public Sub Bug14079()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Interface I
Class Goo
Shared Sub Boo()
End Sub
End Class
End Interface
Class D
Sub Goo()
End Sub
Interface I2
Inherits I
Shadows Class Goo(Of T)
End Class
Class C
Sub Bar()
Goo.Boo()
End Sub
End Class
End Interface
End Class
</file>
</compilation>)
CompilationUtils.AssertNoDiagnostics(compilation)
End Sub
<Fact(), WorkItem(531293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531293")>
Public Sub Bug17900()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4817">
<file name="a.vb">
Imports Undefined
Module Program
Event E
Sub Main()
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC40056: Namespace or type specified in the Imports 'Undefined' 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.
Imports Undefined
~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_01()
Dim compilation = CompilationUtils.CreateEmptyCompilation(
<compilation>
<file name="a.vb">
Imports System
Imports System.Windows.Forms
Module Module1
Sub Main()
Dim x As ComponentModel.INotifyPropertyChanged = Nothing 'BIND1:"ComponentModel"
End Sub
End Module
</file>
</compilation>, references:={Net451.mscorlib, Net451.System, Net451.MicrosoftVisualBasic, Net451.SystemWindowsForms})
CompilationUtils.AssertNoDiagnostics(compilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info = semanticModel.GetSymbolInfo(node)
Dim ns = DirectCast(info.Symbol, NamespaceSymbol)
Assert.Equal(NamespaceKind.Module, ns.NamespaceKind)
Assert.Equal("System.ComponentModel", ns.ToTestDisplayString())
Assert.Equal({"System.ComponentModel", "System.Windows.Forms.ComponentModel"},
semanticModel.LookupNamespacesAndTypes(node.Position, name:="ComponentModel").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"System.ComponentModel", "System.Windows.Forms.ComponentModel"},
semanticModel.LookupSymbols(node.Position, name:="ComponentModel").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports Windows.Foundation
Module Module1
Sub Main()
Diagnostics.Debug.WriteLine("") 'BIND1:"Diagnostics"
Dim x = Diagnostics
Diagnostics
End Sub
End Module
</file>
</compilation>, WinRtRefs)
CompilationUtils.AssertTheseDiagnostics(compilation, <expected>
BC30112: 'Diagnostics' is a namespace and cannot be used as an expression.
Dim x = Diagnostics
~~~~~~~~~~~
BC30112: 'Diagnostics' is a namespace and cannot be used as an expression.
Diagnostics
~~~~~~~~~~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info = semanticModel.GetSymbolInfo(node)
Dim ns = DirectCast(info.Symbol, NamespaceSymbol)
Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind)
Assert.Equal("System.Diagnostics", ns.ToTestDisplayString())
Assert.Equal({"System.Diagnostics", "Windows.Foundation.Diagnostics"},
semanticModel.LookupNamespacesAndTypes(node.Position, name:="Diagnostics").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"System.Diagnostics", "Windows.Foundation.Diagnostics"},
semanticModel.LookupSymbols(node.Position, name:="Diagnostics").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_03()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports NS1
Imports NS2
Module Module1
Sub Main()
NS3. 'BIND1:"NS3"
NS4.T1.M1() 'BIND2:"NS4"
End Sub
End Module
Namespace NS1
Namespace NS3
Namespace NS4
Class T1
Shared Sub M1()
End Sub
End Class
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS3
Namespace NS4
Class T2
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>)
CompilationUtils.AssertNoDiagnostics(compilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Dim info2 = semanticModel.GetSymbolInfo(node2)
Dim ns2 = DirectCast(info2.Symbol, NamespaceSymbol)
Assert.Equal(NamespaceKind.Module, ns2.NamespaceKind)
Assert.Equal("NS1.NS3.NS4", ns2.ToTestDisplayString())
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info1 = semanticModel.GetSymbolInfo(node1)
Dim ns1 = DirectCast(info1.Symbol, NamespaceSymbol)
Assert.Equal(NamespaceKind.Module, ns1.NamespaceKind)
Assert.Equal("NS1.NS3", ns1.ToTestDisplayString())
Assert.Equal({"NS1.NS3", "NS2.NS3"},
semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS3").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS3", "NS2.NS3"},
semanticModel.LookupSymbols(node1.Position, name:="NS3").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_04()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS4
Imports NS5
Imports NS9
Module Module1
Sub Main()
Dim x = GetType(NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
T1) 'BIND3:"T1"
End Sub
Class Test1
Inherits NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
T1 'BIND6:"T1"
End Class
Sub Main2()
Dim x = NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
T1. 'BIND9:"T1"
M1()
End Sub
Sub Main3()
Dim x = GetType(NS6) 'BIND10:"NS6"
Dim y = GetType(NS6. 'BIND11:"NS6"
NS7) 'BIND12:"NS7"
End Sub
Class Test2
Inherits NS6 'BIND13:"NS6"
End Class
Class Test3
Inherits NS6. 'BIND14:"NS6"
NS7 'BIND15:"NS7"
End Class
Sub Main4()
NS6 'BIND16:"NS6"
NS6. 'BIND17:"NS6"
NS7 'BIND18:"NS7"
End Sub
<NS6> 'BIND19:"NS6"
<NS6. 'BIND20:"NS6"
NS7> 'BIND21:"NS7"
<NS6. 'BIND22:"NS6"
NS7. 'BIND23:"NS7"
T1> 'BIND24:"T1"
Class Test4
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS4
Namespace NS6
Namespace NS7
Namespace T1
Class T2
End Class
End Namespace
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'.
Dim x = GetType(NS6. 'BIND1:"NS6"
~~~~~~~~~~~~~~~~~~
BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'.
Inherits NS6. 'BIND4:"NS6"
~~~~~~~~~~~~~~~~~~
BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'.
Dim x = NS6. 'BIND7:"NS6"
~~~~~~~~~~~~~~~~~~
BC30182: Type expected.
Dim x = GetType(NS6) 'BIND10:"NS6"
~~~
BC30182: Type expected.
Dim y = GetType(NS6. 'BIND11:"NS6"
~~~~~~~~~~~~~~~~~~~
BC30182: Type expected.
Inherits NS6 'BIND13:"NS6"
~~~
BC30182: Type expected.
Inherits NS6. 'BIND14:"NS6"
~~~~~~~~~~~~~~~~~~~
BC30112: 'NS6' is a namespace and cannot be used as an expression.
NS6 'BIND16:"NS6"
~~~
BC30112: 'NS6.NS7' is a namespace and cannot be used as an expression.
NS6. 'BIND17:"NS6"
~~~~~~~~~~~~~~~~~~~
BC30182: Type expected.
<NS6> 'BIND19:"NS6"
~~~
BC30182: Type expected.
<NS6. 'BIND20:"NS6"
~~~~~~~~~~~~~~~~~~~
BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'.
<NS6. 'BIND22:"NS6"
~~~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(24) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9, 24}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason)
' Content of this list should determine content of lists below !!!
Assert.Equal({"NS1.NS6.NS7.T1", "NS2.NS6.NS7.T1", "NS4.NS6.NS7.T1", "NS5.NS6.NS7.T1"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {2, 5, 8, 23}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info2.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason)
Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS4.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {1, 4, 7, 22}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info1.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS4.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {10, 13, 16, 19}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info2.Symbol)
Assert.Equal(If(i = 16, CandidateReason.Ambiguous, If(i = 19, CandidateReason.NotAnAttributeType, CandidateReason.NotATypeOrNamespace)), info2.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {12, 15, 18, 21}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(If(i = 18, CandidateReason.Ambiguous, If(i = 21, CandidateReason.NotAnAttributeType, CandidateReason.NotATypeOrNamespace)), info3.CandidateReason)
' Content of this list should determine content of lists below !!!
Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS4.NS6.NS7", "NS5.NS6.NS7", "NS9.NS6.NS7"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {11, 14, 17, 20}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_05()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS4
Imports NS5
Imports NS9
Module Module1
Sub Main()
Dim x = GetType(NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
T1) 'BIND3:"T1"
End Sub
Class Test1
Inherits NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
T1 'BIND6:"T1"
End Class
Sub Main2()
NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
T1. 'BIND9:"T1"
M1()
End Sub
<NS6. 'BIND10:"NS6"
NS7. 'BIND11:"NS7"
T1> 'BIND12:"T1"
Class Test2
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Class T1
Inherits System.Attribute
Shared Sub M1()
End Sub
End Class
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Class T2
End Class
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Class T1
End Class
End Namespace
End Namespace
End Namespace
Namespace NS4
Namespace NS6
Namespace NS7
Namespace T4
Class T2
End Class
End Namespace
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertNoDiagnostics(compilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(12) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6.NS7.T1", info3.Symbol.ToTestDisplayString())
Next
Dim info12 = semanticModel.GetSymbolInfo(nodes(12))
Assert.Equal("Sub NS1.NS6.NS7.T1..ctor()", info12.Symbol.ToTestDisplayString())
For Each i In {2, 5, 8, 11}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind)
Next
For Each i In {1, 4, 7, 10}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_06()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Sub Main()
Dim x = NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
M1() 'BIND3:"M1"
Dim y = GetType(NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
M1) 'BIND6:"M1"
End Sub
<NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
M1> 'BIND9:"M1"
Class Test1
Inherits NS6. 'BIND10:"NS6"
NS7. 'BIND11:"NS7"
M1 'BIND12:"M1"
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30562: 'M1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.T1, NS2.NS6.NS7.T1, NS5.NS6.NS7.T1'.
Dim x = NS6. 'BIND1:"NS6"
~~~~~~~~~~~~~~~~~~
BC30002: Type 'NS6.NS7.M1' is not defined.
Dim y = GetType(NS6. 'BIND4:"NS6"
~~~~~~~~~~~~~~~~~~
BC30002: Type 'NS6.NS7.M1' is not defined.
<NS6. 'BIND7:"NS6"
~~~~~~~~~~~~~~~~~~
BC30002: Type 'NS6.NS7.M1' is not defined.
Inherits NS6. 'BIND10:"NS6"
~~~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(12) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9, 12}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(If(i = 3, CandidateReason.Ambiguous, CandidateReason.NotATypeOrNamespace), info3.CandidateReason)
' Content of this list should determine content of lists below !!!
Assert.Equal({"Sub NS1.NS6.NS7.T1.M1()", "Sub NS2.NS6.NS7.T1.M1()", "Sub NS5.NS6.NS7.T1.M1()"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {2, 5, 8, 11}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info2.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason)
Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {1, 4, 7, 10}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info1.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_07()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Sub Main()
Dim x = NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
M1() 'BIND3:"M1"
End Sub
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module T1
Sub M1(x as Integer)
End Sub
Sub M1(x as Long)
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'M1' accepts this number of arguments.
M1() 'BIND3:"M1"
~~
</expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Dim info3 = semanticModel.GetSymbolInfo(node3)
Assert.Null(info3.Symbol)
Assert.Equal(CandidateReason.OverloadResolutionFailure, info3.CandidateReason)
Assert.Equal({"Sub NS1.NS6.NS7.T1.M1(x As System.Int32)", "Sub NS1.NS6.NS7.T1.M1(x As System.Int64)"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Dim info2 = semanticModel.GetSymbolInfo(node2)
Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info1 = semanticModel.GetSymbolInfo(node1)
Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(node1.Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_08()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Sub Main()
NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
M1() 'BIND3:"M1"
End Sub
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module T1
Sub M1()
End Sub
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module T1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
</file>
</compilation>)
CompilationUtils.AssertNoDiagnostics(compilation)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3)
Dim info3 = semanticModel.GetSymbolInfo(node3)
Assert.Equal("Sub NS1.NS6.NS7.T1.M1()", info3.Symbol.ToTestDisplayString())
Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2)
Dim info2 = semanticModel.GetSymbolInfo(node2)
Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind)
Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1)
Dim info1 = semanticModel.GetSymbolInfo(node1)
Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(node1.Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_09()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Class Test1
Inherits NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
T1 'BIND3:"T1"
End Class
Sub Main()
NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
T1 'BIND6:"T1"
Dim x = GetType(NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
T1) 'BIND9:"T1"
End Sub
<NS6. 'BIND10:"NS6"
NS7. 'BIND11:"NS7"
T1> 'BIND12:"T1"
Class Test2
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module Module1
Class T1
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module Module1
Class T1
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module Module1
Class T1
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module Module1
Class T1
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'.
Inherits NS6. 'BIND1:"NS6"
~~~~~~~~~~~~~~~~~~
BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'.
NS6. 'BIND4:"NS6"
~~~~~~~~~~~~~~~~~~
BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'.
Dim x = GetType(NS6. 'BIND7:"NS6"
~~~~~~~~~~~~~~~~~~
BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'.
<NS6. 'BIND10:"NS6"
~~~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(12) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9, 12}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info3.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason)
' Content of this list should determine content of lists below !!!
Assert.Equal({"NS1.NS6.NS7.Module1.T1", "NS2.NS6.NS7.Module1.T1", "NS5.NS6.NS7.Module1.T1"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {2, 5, 8, 11}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info2.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason)
Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
For Each i In {1, 4, 7, 10}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Null(info1.Symbol)
Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()>
Public Sub AmbiguousNamespaces_10()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports NS1
Imports NS2
Imports NS3
Imports NS5
Imports NS9
Module Module1
Class Test1
Inherits NS6. 'BIND1:"NS6"
NS7. 'BIND2:"NS7"
T1 'BIND3:"T1"
End Class
Sub Main()
NS6. 'BIND4:"NS6"
NS7. 'BIND5:"NS7"
T1 'BIND6:"T1"
Dim x = GetType(NS6. 'BIND7:"NS6"
NS7. 'BIND8:"NS7"
T1) 'BIND9:"T1"
End Sub
<NS6. 'BIND10:"NS6"
NS7. 'BIND11:"NS7"
T1> 'BIND12:"T1"
Class Test2
End Class
End Module
Namespace NS1
Namespace NS6
Namespace NS7
Module Module1
Class T1
Inherits System.Attribute
End Class
End Module
End Namespace
End Namespace
End Namespace
Namespace NS2
Namespace NS6
Namespace NS7
Module Module1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS3
Namespace NS6
Namespace NS8
Module Module1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS5
Namespace NS6
Namespace NS7
Module Module1
End Module
End Namespace
End Namespace
End Namespace
Namespace NS9
Namespace NS6
Namespace NS7
Class T3
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30109: 'Module1.T1' is a class type and cannot be used as an expression.
NS6. 'BIND4:"NS6"
~~~~~~~~~~~~~~~~~~
]]></expected>)
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel)
Dim nodes(12) As IdentifierNameSyntax
For i As Integer = 1 To nodes.Length - 1
nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i)
Next
For Each i In {3, 6, 9}
Dim info3 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6.NS7.Module1.T1", info3.Symbol.ToTestDisplayString())
Next
Dim info12 = semanticModel.GetSymbolInfo(nodes(12))
Assert.Equal("Sub NS1.NS6.NS7.Module1.T1..ctor()", info12.Symbol.ToTestDisplayString())
For Each i In {2, 5, 8, 11}
Dim info2 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind)
Next
For Each i In {1, 4, 7, 10}
Dim info1 = semanticModel.GetSymbolInfo(nodes(i))
Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString())
Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind)
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"},
semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable().
Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray())
Next
End Sub
<Fact()> <WorkItem(842056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842056")>
Public Sub AmbiguousNamespaces_11()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports A
Imports B
Namespace A.X
Class C
End Class
End Namespace
Namespace B.X
Class C
End Class
End Namespace
Module M
Dim c As X.C
End Module
]]></file>
</compilation>, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC37229: 'C' is ambiguous between declarations in namespaces 'A.X, B.X'.
Dim c As X.C
~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants01()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime = DateTime,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
vbCompilation.VerifyDiagnostics() ' no obsolete diagnostic - we select the first one of the given name
CompileAndVerify(vbCompilation, expectedOutput:="2")
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants01b()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime = DateTime,
DATETIME = DateTime,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.Datetime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
vbCompilation.VerifyDiagnostics() ' no obsolete diagnostic - we select the first one of the given name
CompileAndVerify(vbCompilation, expectedOutput:="2")
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
System.Console.WriteLine(CInt(Color.DateTime))
~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02b()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime,
DATETIME,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
System.Console.WriteLine(CInt(Color.DateTime))
~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02c()
Dim csCompilation = CreateCSharpCompilation("CSEnum",
<![CDATA[
public enum Color
{
Red,
Green,
DateTime,
[System.Obsolete] Datetime = DateTime,
[System.Obsolete] DATETIME,
Blue,
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
System.Console.WriteLine(CInt(Color.DateTime))
~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02d()
Dim vbCompilation1 = CreateVisualBasicCompilation("VBEnum",
<![CDATA[
Public Enum Color
Red
Green
DateTime
<System.Obsolete> Datetime = DateTime
DATETIME
Blue
End Enum
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
CompilationUtils.AssertTheseDiagnostics(vbCompilation1,
<expected><![CDATA[
BC31421: 'Datetime' is already declared in this enum.
<System.Obsolete> Datetime = DateTime
~~~~~~~~
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
<System.Obsolete> Datetime = DateTime
~~~~~~~~
BC31421: 'DATETIME' is already declared in this enum.
DATETIME
~~~~~~~~
]]></expected>)
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedAssemblies:={New VisualBasicCompilationReference(vbCompilation1), MscorlibRef, MsvbRef})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'.
System.Console.WriteLine(CInt(Color.DateTime))
~~~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")>
Public Sub AmbiguousEnumConstants02e()
Dim vbCompilation1 = CreateVisualBasicCompilation("VBEnum",
<![CDATA[
Public Enum Color
Red
Green
DateTime
<System.Obsolete> Datetime = 2
Blue
End Enum
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
CompilationUtils.AssertTheseDiagnostics(vbCompilation1,
<expected><![CDATA[
BC31421: 'Datetime' is already declared in this enum.
<System.Obsolete> Datetime = 2
~~~~~~~~
]]></expected>)
Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient",
<![CDATA[
Public Module Program
Sub Main()
System.Console.WriteLine(CInt(Color.DateTime))
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedAssemblies:={New VisualBasicCompilationReference(vbCompilation1), MscorlibRef, MsvbRef})
CompilationUtils.AssertTheseDiagnostics(vbCompilation,
<expected><![CDATA[
]]></expected>)
CompileAndVerify(vbCompilation, expectedOutput:="2")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,491 | Make method extensions | No need for these to be instance methods on ABstractSyntaxFacts | CyrusNajmabadi | "2021-09-17T20:59:25Z" | "2021-09-18T00:30:21Z" | a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d | b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6 | Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts | ./docs/features/ExperimentalAttribute.md | ExperimentalAttribute
=====================
Report warnings for references to types and members marked with `Windows.Foundation.Metadata.ExperimentalAttribute`.
```
namespace Windows.Foundation.Metadata
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
AttributeTargets.Interface | AttributeTargets.Delegate,
AllowMultiple = false)]
public sealed class ExperimentalAttribute : Attribute
{
}
}
```
## Warnings
The warning message is a specific message, where `'{0}'` is the fully-qualified type or member name.
```
'{0}' is for evaluation purposes only and is subject to change or removal in future updates.
```
The warning is reported for any reference to a type or member marked with the attribute.
(The `AttributeUsage` is for types only so the attribute cannot be applied to non-type members from C# or VB,
but the attribute could be applied to non-type members outside of C# or VB.)
```
[Experimental]
class A
{
internal object F;
internal static object G;
internal class B { }
}
class C
{
static void Main()
{
F(default(A)); // warning CS08305: 'A' is for evaluation purposes only ...
F(typeof(A)); // warning CS08305: 'A' is for evaluation purposes only ...
F(nameof(A)); // warning CS08305: 'A' is for evaluation purposes only ...
var a = new A(); // warning CS08305: 'A' is for evaluation purposes only ...
F(a.F);
F(A.G); // warning CS08305: 'A' is for evaluation purposes only ...
F<A.B>(null); // warning CS08305: 'A' is for evaluation purposes only ...
}
static void F<T>(T t)
{
}
}
```
The attribute is not inherited from base types or overridden members.
```
[Experimental]
class A<T>
{
[Experimental]
internal virtual void F()
{
}
}
class B : A<int> // warning CS08305: 'A<int>' is for evaluation purposes only ...
{
internal override void F()
{
base.F(); // warning CS08305: 'A<int>.F' is for evaluation purposes only ...
}
}
class C
{
static void F(A<object> a, B b) // warning CS08305: 'A<object>' is for evaluation purposes only ...
{
a.F(); // warning CS08305: 'A<object>.F' is for evaluation purposes only ...
b.F();
}
}
```
There is no automatic suppression of warnings: warnings are generated for all references, even within `[Experimental]` members.
Suppressing the warning requires an explicit compiler option or `#pragma`.
```
[Experimental] enum E { }
[Experimental]
class C
{
private C(E e) // warning CS08305: 'E' is for evaluation purposes only ...
{
}
internal static C Create() // warning CS08305: 'C' is for evaluation purposes only ...
{
return Create(0);
}
#pragma warning disable 8305
internal static C Create(E e)
{
return new C(e);
}
}
```
## ObsoleteAttribute and DeprecatedAttribute
`ExperimentalAttribute` is independent of `System.ObsoleteAttribute` or `Windows.Framework.Metadata.DeprecatedAttribute`.
Warnings for `[Experimental]` are reported within `[Obsolete]` or `[Deprecated]` members.
Warnings and errors for `[Obsolete]` and `[Deprecated]` are reported inside `[Experimental]` members.
```
[Obsolete]
class A
{
static object F() => new C(); // warning CS08305: 'C' is for evaluation purposes only ...
}
[Deprecated(null, DeprecationType.Deprecate, 0)]
class B
{
static object F() => new C(); // warning CS08305: 'C' is for evaluation purposes only ...
}
[Experimental]
class C
{
static object F() => new B(); // warning CS0612: 'B' is obsolete
}
```
Warnings and errors for `[Obsolete]` and `[Deprecated]` are reported instead of `[Experimental]` if there are multiple attributes.
```
[Obsolete]
[Experimental]
class A
{
}
[Experimental]
[Deprecated(null, DeprecationType.Deprecate, 0)]
class B
{
}
class C
{
static A F() => null; // warning CS0612: 'A' is obsolete
static B G() => null; // warning CS0612: 'B' is obsolete
}
``` | ExperimentalAttribute
=====================
Report warnings for references to types and members marked with `Windows.Foundation.Metadata.ExperimentalAttribute`.
```
namespace Windows.Foundation.Metadata
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
AttributeTargets.Interface | AttributeTargets.Delegate,
AllowMultiple = false)]
public sealed class ExperimentalAttribute : Attribute
{
}
}
```
## Warnings
The warning message is a specific message, where `'{0}'` is the fully-qualified type or member name.
```
'{0}' is for evaluation purposes only and is subject to change or removal in future updates.
```
The warning is reported for any reference to a type or member marked with the attribute.
(The `AttributeUsage` is for types only so the attribute cannot be applied to non-type members from C# or VB,
but the attribute could be applied to non-type members outside of C# or VB.)
```
[Experimental]
class A
{
internal object F;
internal static object G;
internal class B { }
}
class C
{
static void Main()
{
F(default(A)); // warning CS08305: 'A' is for evaluation purposes only ...
F(typeof(A)); // warning CS08305: 'A' is for evaluation purposes only ...
F(nameof(A)); // warning CS08305: 'A' is for evaluation purposes only ...
var a = new A(); // warning CS08305: 'A' is for evaluation purposes only ...
F(a.F);
F(A.G); // warning CS08305: 'A' is for evaluation purposes only ...
F<A.B>(null); // warning CS08305: 'A' is for evaluation purposes only ...
}
static void F<T>(T t)
{
}
}
```
The attribute is not inherited from base types or overridden members.
```
[Experimental]
class A<T>
{
[Experimental]
internal virtual void F()
{
}
}
class B : A<int> // warning CS08305: 'A<int>' is for evaluation purposes only ...
{
internal override void F()
{
base.F(); // warning CS08305: 'A<int>.F' is for evaluation purposes only ...
}
}
class C
{
static void F(A<object> a, B b) // warning CS08305: 'A<object>' is for evaluation purposes only ...
{
a.F(); // warning CS08305: 'A<object>.F' is for evaluation purposes only ...
b.F();
}
}
```
There is no automatic suppression of warnings: warnings are generated for all references, even within `[Experimental]` members.
Suppressing the warning requires an explicit compiler option or `#pragma`.
```
[Experimental] enum E { }
[Experimental]
class C
{
private C(E e) // warning CS08305: 'E' is for evaluation purposes only ...
{
}
internal static C Create() // warning CS08305: 'C' is for evaluation purposes only ...
{
return Create(0);
}
#pragma warning disable 8305
internal static C Create(E e)
{
return new C(e);
}
}
```
## ObsoleteAttribute and DeprecatedAttribute
`ExperimentalAttribute` is independent of `System.ObsoleteAttribute` or `Windows.Framework.Metadata.DeprecatedAttribute`.
Warnings for `[Experimental]` are reported within `[Obsolete]` or `[Deprecated]` members.
Warnings and errors for `[Obsolete]` and `[Deprecated]` are reported inside `[Experimental]` members.
```
[Obsolete]
class A
{
static object F() => new C(); // warning CS08305: 'C' is for evaluation purposes only ...
}
[Deprecated(null, DeprecationType.Deprecate, 0)]
class B
{
static object F() => new C(); // warning CS08305: 'C' is for evaluation purposes only ...
}
[Experimental]
class C
{
static object F() => new B(); // warning CS0612: 'B' is obsolete
}
```
Warnings and errors for `[Obsolete]` and `[Deprecated]` are reported instead of `[Experimental]` if there are multiple attributes.
```
[Obsolete]
[Experimental]
class A
{
}
[Experimental]
[Deprecated(null, DeprecationType.Deprecate, 0)]
class B
{
}
class C
{
static A F() => null; // warning CS0612: 'A' is obsolete
static B G() => null; // warning CS0612: 'B' is obsolete
}
``` | -1 |
dotnet/roslyn | 56,491 | Make method extensions | No need for these to be instance methods on ABstractSyntaxFacts | CyrusNajmabadi | "2021-09-17T20:59:25Z" | "2021-09-18T00:30:21Z" | a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d | b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6 | Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts | ./src/Compilers/VisualBasic/Portable/PublicAPI.Unshipped.txt | Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic16_9 = 1609 -> Microsoft.CodeAnalysis.VisualBasic.LanguageVersion
Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Overrides Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.GetLineMappings(cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Collections.Generic.IEnumerable(Of Microsoft.CodeAnalysis.LineMapping)
Overrides Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.GetUsedAssemblyReferences(cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.MetadataReference)
*REMOVED*Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing, driverOptions As Microsoft.CodeAnalysis.GeneratorDriverOptions = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText), parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver | Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic16_9 = 1609 -> Microsoft.CodeAnalysis.VisualBasic.LanguageVersion
Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Overrides Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.GetLineMappings(cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Collections.Generic.IEnumerable(Of Microsoft.CodeAnalysis.LineMapping)
Overrides Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.GetUsedAssemblyReferences(cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.MetadataReference)
*REMOVED*Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing, driverOptions As Microsoft.CodeAnalysis.GeneratorDriverOptions = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText), parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver | -1 |
dotnet/roslyn | 56,491 | Make method extensions | No need for these to be instance methods on ABstractSyntaxFacts | CyrusNajmabadi | "2021-09-17T20:59:25Z" | "2021-09-18T00:30:21Z" | a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d | b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6 | Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts | ./src/Tools/ExternalAccess/FSharp/xlf/ExternalAccessFSharpResources.fr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="fr" original="../ExternalAccessFSharpResources.resx">
<body>
<trans-unit id="AddAssemblyReference">
<source>Add an assembly reference to '{0}'</source>
<target state="translated">Ajouter une référence d'assembly à '{0}'</target>
<note />
</trans-unit>
<trans-unit id="AddNewKeyword">
<source>Add 'new' keyword</source>
<target state="translated">Ajouter le mot clé 'new'</target>
<note />
</trans-unit>
<trans-unit id="AddProjectReference">
<source>Add a project reference to '{0}'</source>
<target state="translated">Ajouter une référence de projet à '{0}'</target>
<note />
</trans-unit>
<trans-unit id="CannotDetermineSymbol">
<source>Cannot determine the symbol under the caret</source>
<target state="translated">Impossible de déterminer le symbole sous le point d'insertion</target>
<note />
</trans-unit>
<trans-unit id="CannotNavigateUnknown">
<source>Cannot navigate to the requested location</source>
<target state="translated">Impossible d'accéder à l'emplacement demandé</target>
<note />
</trans-unit>
<trans-unit id="ExceptionsHeader">
<source>Exceptions:</source>
<target state="translated">Exceptions :</target>
<note />
</trans-unit>
<trans-unit id="FSharpDisposablesClassificationType">
<source>F# Disposable Types</source>
<target state="translated">Types F# pouvant être supprimés</target>
<note />
</trans-unit>
<trans-unit id="FSharpFunctionsOrMethodsClassificationType">
<source>F# Functions / Methods</source>
<target state="translated">Fonctions / méthodes F#</target>
<note />
</trans-unit>
<trans-unit id="FSharpMutableVarsClassificationType">
<source>F# Mutable Variables / Reference Cells</source>
<target state="translated">Variables mutables / Cellules de référence F#</target>
<note />
</trans-unit>
<trans-unit id="FSharpPrintfFormatClassificationType">
<source>F# Printf Format</source>
<target state="translated">Format Printf F#</target>
<note />
</trans-unit>
<trans-unit id="FSharpPropertiesClassificationType">
<source>F# Properties</source>
<target state="translated">Propriétés F#</target>
<note />
</trans-unit>
<trans-unit id="GenericParametersHeader">
<source>Generic parameters:</source>
<target state="translated">Paramètres génériques :</target>
<note />
</trans-unit>
<trans-unit id="ImplementInterface">
<source>Implement interface</source>
<target state="translated">Implémenter l'interface</target>
<note />
</trans-unit>
<trans-unit id="ImplementInterfaceWithoutTypeAnnotation">
<source>Implement interface without type annotation</source>
<target state="translated">Implémenter l'interface sans annotation de type</target>
<note />
</trans-unit>
<trans-unit id="LocatingSymbol">
<source>Locating the symbol under the caret...</source>
<target state="translated">Localisation du symbole sous le point d'insertion...</target>
<note />
</trans-unit>
<trans-unit id="NameCanBeSimplified">
<source>Name can be simplified.</source>
<target state="translated">Le nom peut être simplifié.</target>
<note />
</trans-unit>
<trans-unit id="NavigateToFailed">
<source>Navigate to symbol failed: {0}</source>
<target state="translated">Échec de l'accès au symbole : {0}</target>
<note />
</trans-unit>
<trans-unit id="NavigatingTo">
<source>Navigating to symbol...</source>
<target state="translated">Accès au symbole...</target>
<note />
</trans-unit>
<trans-unit id="PrefixValueNameWithUnderscore">
<source>Prefix '{0}' with underscore</source>
<target state="translated">Faire précéder '{0}' d'un trait de soulignement</target>
<note />
</trans-unit>
<trans-unit id="RemoveUnusedOpens">
<source>Remove unused open declarations</source>
<target state="translated">Supprimer les déclarations open inutilisées</target>
<note />
</trans-unit>
<trans-unit id="RenameValueToDoubleUnderscore">
<source>Rename '{0}' to '__'</source>
<target state="translated">Renommer '{0}' en '__'</target>
<note />
</trans-unit>
<trans-unit id="RenameValueToUnderscore">
<source>Rename '{0}' to '_'</source>
<target state="translated">Renommer '{0}' en '_'</target>
<note />
</trans-unit>
<trans-unit id="SimplifyName">
<source>Simplify name</source>
<target state="translated">Simplifier le nom</target>
<note />
</trans-unit>
<trans-unit id="TheValueIsUnused">
<source>The value is unused</source>
<target state="translated">La valeur est inutilisée</target>
<note />
</trans-unit>
<trans-unit id="UnusedOpens">
<source>Open declaration can be removed.</source>
<target state="translated">La déclaration open peut être supprimée.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="fr" original="../ExternalAccessFSharpResources.resx">
<body>
<trans-unit id="AddAssemblyReference">
<source>Add an assembly reference to '{0}'</source>
<target state="translated">Ajouter une référence d'assembly à '{0}'</target>
<note />
</trans-unit>
<trans-unit id="AddNewKeyword">
<source>Add 'new' keyword</source>
<target state="translated">Ajouter le mot clé 'new'</target>
<note />
</trans-unit>
<trans-unit id="AddProjectReference">
<source>Add a project reference to '{0}'</source>
<target state="translated">Ajouter une référence de projet à '{0}'</target>
<note />
</trans-unit>
<trans-unit id="CannotDetermineSymbol">
<source>Cannot determine the symbol under the caret</source>
<target state="translated">Impossible de déterminer le symbole sous le point d'insertion</target>
<note />
</trans-unit>
<trans-unit id="CannotNavigateUnknown">
<source>Cannot navigate to the requested location</source>
<target state="translated">Impossible d'accéder à l'emplacement demandé</target>
<note />
</trans-unit>
<trans-unit id="ExceptionsHeader">
<source>Exceptions:</source>
<target state="translated">Exceptions :</target>
<note />
</trans-unit>
<trans-unit id="FSharpDisposablesClassificationType">
<source>F# Disposable Types</source>
<target state="translated">Types F# pouvant être supprimés</target>
<note />
</trans-unit>
<trans-unit id="FSharpFunctionsOrMethodsClassificationType">
<source>F# Functions / Methods</source>
<target state="translated">Fonctions / méthodes F#</target>
<note />
</trans-unit>
<trans-unit id="FSharpMutableVarsClassificationType">
<source>F# Mutable Variables / Reference Cells</source>
<target state="translated">Variables mutables / Cellules de référence F#</target>
<note />
</trans-unit>
<trans-unit id="FSharpPrintfFormatClassificationType">
<source>F# Printf Format</source>
<target state="translated">Format Printf F#</target>
<note />
</trans-unit>
<trans-unit id="FSharpPropertiesClassificationType">
<source>F# Properties</source>
<target state="translated">Propriétés F#</target>
<note />
</trans-unit>
<trans-unit id="GenericParametersHeader">
<source>Generic parameters:</source>
<target state="translated">Paramètres génériques :</target>
<note />
</trans-unit>
<trans-unit id="ImplementInterface">
<source>Implement interface</source>
<target state="translated">Implémenter l'interface</target>
<note />
</trans-unit>
<trans-unit id="ImplementInterfaceWithoutTypeAnnotation">
<source>Implement interface without type annotation</source>
<target state="translated">Implémenter l'interface sans annotation de type</target>
<note />
</trans-unit>
<trans-unit id="LocatingSymbol">
<source>Locating the symbol under the caret...</source>
<target state="translated">Localisation du symbole sous le point d'insertion...</target>
<note />
</trans-unit>
<trans-unit id="NameCanBeSimplified">
<source>Name can be simplified.</source>
<target state="translated">Le nom peut être simplifié.</target>
<note />
</trans-unit>
<trans-unit id="NavigateToFailed">
<source>Navigate to symbol failed: {0}</source>
<target state="translated">Échec de l'accès au symbole : {0}</target>
<note />
</trans-unit>
<trans-unit id="NavigatingTo">
<source>Navigating to symbol...</source>
<target state="translated">Accès au symbole...</target>
<note />
</trans-unit>
<trans-unit id="PrefixValueNameWithUnderscore">
<source>Prefix '{0}' with underscore</source>
<target state="translated">Faire précéder '{0}' d'un trait de soulignement</target>
<note />
</trans-unit>
<trans-unit id="RemoveUnusedOpens">
<source>Remove unused open declarations</source>
<target state="translated">Supprimer les déclarations open inutilisées</target>
<note />
</trans-unit>
<trans-unit id="RenameValueToDoubleUnderscore">
<source>Rename '{0}' to '__'</source>
<target state="translated">Renommer '{0}' en '__'</target>
<note />
</trans-unit>
<trans-unit id="RenameValueToUnderscore">
<source>Rename '{0}' to '_'</source>
<target state="translated">Renommer '{0}' en '_'</target>
<note />
</trans-unit>
<trans-unit id="SimplifyName">
<source>Simplify name</source>
<target state="translated">Simplifier le nom</target>
<note />
</trans-unit>
<trans-unit id="TheValueIsUnused">
<source>The value is unused</source>
<target state="translated">La valeur est inutilisée</target>
<note />
</trans-unit>
<trans-unit id="UnusedOpens">
<source>Open declaration can be removed.</source>
<target state="translated">La déclaration open peut être supprimée.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,491 | Make method extensions | No need for these to be instance methods on ABstractSyntaxFacts | CyrusNajmabadi | "2021-09-17T20:59:25Z" | "2021-09-18T00:30:21Z" | a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d | b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6 | Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.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="../CSharpWorkspaceExtensionsResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">別の値が追加されたら、この値を削除します。</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</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="../CSharpWorkspaceExtensionsResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">別の値が追加されたら、この値を削除します。</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,491 | Make method extensions | No need for these to be instance methods on ABstractSyntaxFacts | CyrusNajmabadi | "2021-09-17T20:59:25Z" | "2021-09-18T00:30:21Z" | a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d | b7d780dba0b1fbe63215bb4ec7c253a5a469d7b6 | Make method extensions. No need for these to be instance methods on ABstractSyntaxFacts | ./src/VisualStudio/IntegrationTest/IntegrationService/Microsoft.VisualStudio.IntegrationTest.IntegrationService.csproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.VisualStudio.IntegrationTest.IntegrationService</RootNamespace>
<TargetFramework>net472</TargetFramework>
<IsShipping>false</IsShipping>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Setup" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.VisualStudio.IntegrationTest.IntegrationService</RootNamespace>
<TargetFramework>net472</TargetFramework>
<IsShipping>false</IsShipping>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Setup" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.CSharp.LanguageServices
{
internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts
{
internal static readonly CSharpSyntaxFacts Instance = new();
protected CSharpSyntaxFacts()
{
}
public bool IsCaseSensitive => true;
public StringComparer StringComparer { get; } = StringComparer.Ordinal;
public SyntaxTrivia ElasticMarker
=> SyntaxFactory.ElasticMarker;
public SyntaxTrivia ElasticCarriageReturnLineFeed
=> SyntaxFactory.ElasticCarriageReturnLineFeed;
public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance;
public bool SupportsIndexingInitializer(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6;
public bool SupportsThrowExpression(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsLocalFunctionDeclaration(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsRecord(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9;
public bool SupportsRecordStruct(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove();
public SyntaxToken ParseToken(string text)
=> SyntaxFactory.ParseToken(text);
public SyntaxTriviaList ParseLeadingTrivia(string text)
=> SyntaxFactory.ParseLeadingTrivia(text);
public string EscapeIdentifier(string identifier)
{
var nullIndex = identifier.IndexOf('\0');
if (nullIndex >= 0)
{
identifier = identifier.Substring(0, nullIndex);
}
var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None;
return needsEscaping ? "@" + identifier : identifier;
}
public bool IsVerbatimIdentifier(SyntaxToken token)
=> token.IsVerbatimIdentifier();
public bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public bool IsReservedKeyword(SyntaxToken token)
=> SyntaxFacts.IsReservedKeyword(token.Kind());
public bool IsContextualKeyword(SyntaxToken token)
=> SyntaxFacts.IsContextualKeyword(token.Kind());
public bool IsPreprocessorKeyword(SyntaxToken token)
=> SyntaxFacts.IsPreprocessorKeyword(token.Kind());
public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
=> syntaxTree.IsPreProcessorDirectiveContext(
position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken)
{
if (syntaxTree == null)
{
return false;
}
return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public bool IsDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is DirectiveTriviaSyntax;
public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info)
{
if (node is LineDirectiveTriviaSyntax lineDirective)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default;
return false;
}
public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsSimpleMemberAccessExpressionName();
}
public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node;
public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberBindingExpressionName();
}
[return: NotNullIfNotNull("node")]
public SyntaxNode? GetStandaloneExpression(SyntaxNode? node)
=> node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node;
public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node)
=> node.GetRootConditionalAccessExpression();
public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is DeclarationExpressionSyntax;
public bool IsAttributeName(SyntaxNode node)
=> SyntaxFacts.IsAttributeName(node);
public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node is ArgumentSyntax arg && arg.NameColon != null;
public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.CheckParent<NameColonSyntax>(p => p.Name == node);
public SyntaxToken? GetNameOfParameter(SyntaxNode? node)
=> (node as ParameterSyntax)?.Identifier;
public SyntaxNode? GetDefaultOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Default;
public SyntaxNode? GetParameterList(SyntaxNode node)
=> node.GetParameterList();
public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList);
public SyntaxToken GetIdentifierOfGenericName(SyntaxNode node)
=> ((GenericNameSyntax)node).Identifier;
public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) &&
usingDirective.Name == node;
public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null;
public void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name)
{
var usingDirective = (UsingDirectiveSyntax)node;
globalKeyword = usingDirective.GlobalKeyword;
alias = usingDirective.Alias!.Name.Identifier;
name = usingDirective.Name;
}
public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is ForEachVariableStatementSyntax;
public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node)
=> node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction();
public Location GetDeconstructionReferenceLocation(SyntaxNode node)
{
return node switch
{
AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(),
ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(),
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
};
}
public bool IsStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node)
{
if (node is BlockSyntax ||
node is ArrowExpressionClauseSyntax)
{
return node.Parent is BaseMethodDeclarationSyntax ||
node.Parent is AccessorDeclarationSyntax;
}
return false;
}
public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node)
=> ((ReturnStatementSyntax)node).Expression;
public bool IsThisConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsBaseConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsQueryKeyword(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.FromKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.InKeyword:
return token.Parent is QueryClauseSyntax;
case SyntaxKind.ByKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.SelectKeyword:
return token.Parent is SelectOrGroupClauseSyntax;
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
return token.Parent is OrderingSyntax;
case SyntaxKind.IntoKeyword:
return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation);
default:
return false;
}
}
public bool IsPredefinedType(SyntaxToken token)
=> TryGetPredefinedType(token, out _);
public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
=> TryGetPredefinedType(token, out var actualType) && actualType == type;
public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private static PredefinedType GetPredefinedType(SyntaxToken token)
{
return (SyntaxKind)token.RawKind switch
{
SyntaxKind.BoolKeyword => PredefinedType.Boolean,
SyntaxKind.ByteKeyword => PredefinedType.Byte,
SyntaxKind.SByteKeyword => PredefinedType.SByte,
SyntaxKind.IntKeyword => PredefinedType.Int32,
SyntaxKind.UIntKeyword => PredefinedType.UInt32,
SyntaxKind.ShortKeyword => PredefinedType.Int16,
SyntaxKind.UShortKeyword => PredefinedType.UInt16,
SyntaxKind.LongKeyword => PredefinedType.Int64,
SyntaxKind.ULongKeyword => PredefinedType.UInt64,
SyntaxKind.FloatKeyword => PredefinedType.Single,
SyntaxKind.DoubleKeyword => PredefinedType.Double,
SyntaxKind.DecimalKeyword => PredefinedType.Decimal,
SyntaxKind.StringKeyword => PredefinedType.String,
SyntaxKind.CharKeyword => PredefinedType.Char,
SyntaxKind.ObjectKeyword => PredefinedType.Object,
SyntaxKind.VoidKeyword => PredefinedType.Void,
_ => PredefinedType.None,
};
}
public bool IsPredefinedOperator(SyntaxToken token)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None;
public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op;
public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private static PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanToken:
return PredefinedOperator.LessThan;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public string GetText(int kind)
=> SyntaxFacts.GetText((SyntaxKind)kind);
public bool IsIdentifierStartCharacter(char c)
=> SyntaxFacts.IsIdentifierStartCharacter(c);
public bool IsIdentifierPartCharacter(char c)
=> SyntaxFacts.IsIdentifierPartCharacter(c);
public bool IsIdentifierEscapeCharacter(char c)
=> c == '@';
public bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public bool IsTypeCharacter(char c) => false;
public bool IsStartOfUnicodeEscapeSequence(char c)
=> c == '\\';
public bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
return true;
default:
return false;
}
}
public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token)
=> token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken);
public bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
// In the order by clause a comma might be bound to ThenBy or ThenByDescending
if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause))
{
return true;
}
return false;
}
public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is PostfixUnaryExpressionSyntax;
public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberBindingExpressionSyntax;
public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression;
public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity)
{
var simpleName = (SimpleNameSyntax)node;
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
public bool LooksGeneric(SyntaxNode simpleName)
=> simpleName.IsKind(SyntaxKind.GenericName) ||
simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken;
public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node)
=> (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression;
public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node)
=> ((MemberBindingExpressionSyntax)node).Name;
public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget)
=> ((MemberAccessExpressionSyntax)node).Expression;
public void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList)
{
var elementAccess = (ElementAccessExpressionSyntax)node;
expression = elementAccess.Expression;
argumentList = elementAccess.ArgumentList;
}
public SyntaxNode GetExpressionOfInterpolation(SyntaxNode node)
=> ((InterpolationSyntax)node).Expression;
public bool IsInStaticContext(SyntaxNode node)
=> node.IsInStaticContext();
public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node)
=> SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.BaseList);
public SyntaxNode GetExpressionOfArgument(SyntaxNode node)
=> ((ArgumentSyntax)node).Expression;
public RefKind GetRefKindOfArgument(SyntaxNode node)
=> ((ArgumentSyntax)node).GetRefKind();
public bool IsArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Argument);
public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node)
{
return node is ArgumentSyntax argument &&
argument.RefOrOutKeyword.Kind() == SyntaxKind.None &&
argument.NameColon == null;
}
public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsInConstantContext();
public bool IsInConstructor(SyntaxNode node)
=> node.GetAncestor<ConstructorDeclarationSyntax>() != null;
public bool IsUnsafeContext(SyntaxNode node)
=> node.IsUnsafeContext();
public SyntaxNode GetNameOfAttribute(SyntaxNode node)
=> ((AttributeSyntax)node).Name;
public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier();
public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node)
=> throw ExceptionUtilities.Unreachable;
public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IdentifierName) &&
node.IsParentKind(SyntaxKind.NameColon) &&
node.Parent.IsParentKind(SyntaxKind.Subpattern);
public bool IsPropertyPatternClause(SyntaxNode node)
=> node.Kind() == SyntaxKind.PropertyPatternClause;
public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> IsMemberInitializerNamedAssignmentIdentifier(node, out _);
public bool IsMemberInitializerNamedAssignmentIdentifier(
[NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance)
{
initializedInstance = null;
if (node is IdentifierNameSyntax identifier &&
identifier.IsLeftSideOfAssignExpression())
{
if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression))
{
var withInitializer = identifier.Parent.GetRequiredParent();
initializedInstance = withInitializer.GetRequiredParent();
return true;
}
else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression))
{
var objectInitializer = identifier.Parent.GetRequiredParent();
if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax)
{
initializedInstance = objectInitializer.Parent;
return true;
}
else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment))
{
initializedInstance = assignment.Left;
return true;
}
}
}
return false;
}
public bool IsElementAccessExpression(SyntaxNode? node)
=> node.IsKind(SyntaxKind.ElementAccessExpression);
[return: NotNullIfNotNull("node")]
public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false)
=> node.ConvertToSingleLine(useElasticTrivia);
public bool IsIndexerMemberCRef(SyntaxNode? node)
=> node.IsKind(SyntaxKind.IndexerMemberCref);
public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (useFullSpan || node.Span.Contains(position))
{
var kind = node.Kind();
if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax))
{
return node;
}
}
node = node.Parent;
}
return null;
}
public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseMethodDeclarationSyntax ||
node is BasePropertyDeclarationSyntax ||
node is EnumMemberDeclarationSyntax ||
node is BaseFieldDeclarationSyntax;
}
public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseNamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
private const string dotToken = ".";
public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null)
{
if (node == null)
{
return string.Empty;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
// return type
var memberDeclaration = node as MemberDeclarationSyntax;
if ((options & DisplayNameOptions.IncludeType) != 0)
{
var type = memberDeclaration.GetMemberType();
if (type != null && !type.IsMissing)
{
builder.Append(type);
builder.Append(' ');
}
}
var names = ArrayBuilder<string?>.GetInstance();
// containing type(s)
var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent;
while (parent is TypeDeclarationSyntax)
{
names.Push(GetName(parent, options));
parent = parent.Parent;
}
// containing namespace(s) in source (if any)
if ((options & DisplayNameOptions.IncludeNamespaces) != 0)
{
while (parent is BaseNamespaceDeclarationSyntax)
{
names.Add(GetName(parent, options));
parent = parent.Parent;
}
}
while (!names.IsEmpty())
{
var name = names.Pop();
if (name != null)
{
builder.Append(name);
builder.Append(dotToken);
}
}
// name (including generic type parameters)
builder.Append(GetName(node, options));
// parameter list (if any)
if ((options & DisplayNameOptions.IncludeParameters) != 0)
{
builder.Append(memberDeclaration.GetParameterList());
}
return pooled.ToStringAndFree();
}
private static string? GetName(SyntaxNode node, DisplayNameOptions options)
{
const string missingTokenPlaceholder = "?";
switch (node.Kind())
{
case SyntaxKind.CompilationUnit:
return null;
case SyntaxKind.IdentifierName:
var identifier = ((IdentifierNameSyntax)node).Identifier;
return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text;
case SyntaxKind.IncompleteMember:
return missingTokenPlaceholder;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options);
}
string? name = null;
if (node is MemberDeclarationSyntax memberDeclaration)
{
if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration)
{
name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString();
}
else
{
var nameToken = memberDeclaration.GetNameToken();
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration)
{
name = "~" + name;
}
if ((options & DisplayNameOptions.IncludeTypeParameters) != 0)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList());
name = pooled.ToStringAndFree();
}
}
else
{
Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember);
name = "?";
}
}
}
else
{
if (node is VariableDeclaratorSyntax fieldDeclarator)
{
var nameToken = fieldDeclarator.Identifier;
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
}
}
}
Debug.Assert(name != null, "Unexpected node type " + node.Kind());
return name;
}
private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (var i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(", ");
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
}
}
public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: true, methodLevel: true);
return list;
}
public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: false, methodLevel: true);
return list;
}
public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration)
=> ((TypeDeclarationSyntax)typeDeclaration).Members;
private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel)
{
Debug.Assert(topLevel || methodLevel);
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (topLevel)
{
list.Add(member);
}
AppendMembers(member, list, topLevel, methodLevel);
continue;
}
if (methodLevel && IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default;
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default;
}
// TODO: currently we only support method for now
if (member is BaseMethodDeclarationSyntax method)
{
if (method.Body == null)
{
return default;
}
return GetBlockBodySpan(method.Body);
}
return default;
}
public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span)
{
switch (node)
{
case ConstructorDeclarationSyntax constructor:
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
case BaseMethodDeclarationSyntax method:
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
case BasePropertyDeclarationSyntax property:
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
case EnumMemberDeclarationSyntax @enum:
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
case BaseFieldDeclarationSyntax field:
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private static TextSpan GetBlockBodySpan(BlockSyntax body)
=> TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
public SyntaxNode? TryGetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
if (parent is MemberAccessExpressionSyntax memberAccess)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is QualifiedNameSyntax qualifiedName)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
if (parent is ObjectCreationExpressionSyntax objectCreation)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// The inside of an interpolated string is treated as its own token so we
// need to force navigation to the parent expression syntax.
if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax)
{
node = parent;
break;
}
// If this node is not parented by a name, we're done.
if (!(parent is NameSyntax))
{
break;
}
node = parent;
}
if (node is VarPatternSyntax)
{
return node;
}
// Patterns are never bindable (though their constituent types/exprs may be).
return node is PatternSyntax ? null : node;
}
public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken)
{
if (root is not CompilationUnitSyntax compilationUnit)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
switch (member)
{
case ConstructorDeclarationSyntax constructor:
constructors.Add(constructor);
continue;
case BaseNamespaceDeclarationSyntax @namespace:
AppendConstructors(@namespace.Members, constructors, cancellationToken);
break;
case ClassDeclarationSyntax @class:
AppendConstructors(@class.Members, constructors, cancellationToken);
break;
case RecordDeclarationSyntax record:
AppendConstructors(record.Members, constructors, cancellationToken);
break;
case StructDeclarationSyntax @struct:
AppendConstructors(@struct.Members, constructors, cancellationToken);
break;
}
}
}
public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.openBrace;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default;
return false;
}
public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return trivia.FullSpan;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return default;
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return default;
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax branch)
{
return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default;
}
}
}
}
return default;
}
public string GetNameForArgument(SyntaxNode? argument)
=> (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty;
public string GetNameForAttributeArgument(SyntaxNode? argument)
=> (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty;
public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfDot();
public SyntaxNode? GetRightSideOfDot(SyntaxNode? node)
{
return (node as QualifiedNameSyntax)?.Right ??
(node as MemberAccessExpressionSyntax)?.Name;
}
public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget)
{
return (node as QualifiedNameSyntax)?.Left ??
(node as MemberAccessExpressionSyntax)?.Expression;
}
public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier();
public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAssignExpression();
public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression();
public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression();
public SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node)
=> ((AssignmentExpressionSyntax)node).Right;
public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) &&
anonObject.NameEquals == null;
public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostIncrementExpression) ||
node.IsParentKind(SyntaxKind.PreIncrementExpression);
public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostDecrementExpression) ||
node.IsParentKind(SyntaxKind.PreDecrementExpression);
public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node);
public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString)
=> ((InterpolatedStringExpressionSyntax)interpolatedString).Contents;
public bool IsVerbatimStringLiteral(SyntaxToken token)
=> token.IsVerbatimStringLiteral();
public bool IsNumericLiteral(SyntaxToken token)
=> token.Kind() == SyntaxKind.NumericLiteralToken;
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode invocationExpression)
=> GetArgumentsOfArgumentList(((InvocationExpressionSyntax)invocationExpression).ArgumentList);
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode objectCreationExpression)
=> ((BaseObjectCreationExpressionSyntax)objectCreationExpression).ArgumentList is { } argumentList
? GetArgumentsOfArgumentList(argumentList)
: default;
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode argumentList)
=> ((BaseArgumentListSyntax)argumentList).Arguments;
public bool IsRegularComment(SyntaxTrivia trivia)
=> trivia.IsRegularComment();
public bool IsDocumentationComment(SyntaxTrivia trivia)
=> trivia.IsDocComment();
public bool IsElastic(SyntaxTrivia trivia)
=> trivia.IsElastic();
public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes)
=> trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes);
public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia)
=> trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia;
public bool IsDocumentationComment(SyntaxNode node)
=> SyntaxFacts.IsDocumentationCommentTrivia(node.Kind());
public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node)
{
return node.IsKind(SyntaxKind.UsingDirective) ||
node.IsKind(SyntaxKind.ExternAliasDirective);
}
public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword);
public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.ModuleKeyword);
private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget)
=> node.IsKind(SyntaxKind.Attribute) &&
node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) &&
attributeList.Target?.Identifier.Kind() == attributeTarget;
private static bool IsMemberDeclaration(SyntaxNode node)
{
// From the C# language spec:
// class-member-declaration:
// constant-declaration
// field-declaration
// method-declaration
// property-declaration
// event-declaration
// indexer-declaration
// operator-declaration
// constructor-declaration
// destructor-declaration
// static-constructor-declaration
// type-declaration
switch (node.Kind())
{
// Because fields declarations can define multiple symbols "public int a, b;"
// We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
case SyntaxKind.VariableDeclarator:
return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) ||
node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
return true;
default:
return false;
}
}
public bool IsDeclaration(SyntaxNode node)
=> SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node);
public bool IsTypeDeclaration(SyntaxNode node)
=> SyntaxFacts.IsTypeDeclaration(node.Kind());
public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement)
=> statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) &&
exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression);
public void GetPartsOfAssignmentStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
GetPartsOfAssignmentExpressionOrStatement(
((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right);
}
public void GetPartsOfAssignmentExpressionOrStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var expression = statement;
if (statement is ExpressionStatementSyntax expressionStatement)
{
expression = expressionStatement.Expression;
}
var assignment = (AssignmentExpressionSyntax)expression;
left = assignment.Left;
operatorToken = assignment.OperatorToken;
right = assignment.Right;
}
public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node)
=> ((SimpleNameSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node)
=> node switch
{
BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier,
DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier,
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node)
=> ((IdentifierNameSyntax)node).Identifier;
public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement)
{
return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains(
(VariableDeclaratorSyntax)declarator);
}
public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2)
=> SyntaxFactory.AreEquivalent(token1, token2);
public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2)
=> SyntaxFactory.AreEquivalent(node1, node2);
public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node)
=> ((InvocationExpressionSyntax)node).Expression;
public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node;
public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node)
=> ((ExpressionStatementSyntax)node).Expression;
public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsExpression);
[return: NotNullIfNotNull("node")]
public SyntaxNode? WalkDownParentheses(SyntaxNode? node)
=> (node as ExpressionSyntax)?.WalkDownParentheses() ?? node;
public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode
{
var tupleExpression = (TupleExpressionSyntax)node;
openParen = tupleExpression.OpenParenToken;
arguments = (SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments;
closeParen = tupleExpression.CloseParenToken;
}
public override bool IsPreprocessorDirective(SyntaxTrivia trivia)
=> SyntaxFacts.IsPreprocessorDirective(trivia.Kind());
public override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken)
=> token.ContainsInterleavedDirective(span, cancellationToken);
public SyntaxTokenList GetModifiers(SyntaxNode? node)
=> node.GetModifiers();
public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers)
=> node.WithModifiers(modifiers);
public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node)
=> ((LocalDeclarationStatementSyntax)node).Declaration.Variables;
public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Initializer;
public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type;
public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node)
=> ((EqualsValueClauseSyntax?)node)?.Value;
public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block);
public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit);
public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node)
{
return node switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement),
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
}
public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode(node => IsExecutableBlock(node));
public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node)
=> IsExecutableBlock(node) || node.IsEmbeddedStatementOwner();
public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node)
{
if (IsExecutableBlock(node))
return GetExecutableBlockStatements(node);
else if (node.GetEmbeddedStatement() is { } embeddedStatement)
return ImmutableArray.Create<SyntaxNode>(embeddedStatement);
else
return ImmutableArray<SyntaxNode>.Empty;
}
public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression)
{
var cast = (CastExpressionSyntax)node;
type = cast.Type;
expression = cast.Expression;
}
public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member)
{
return member.GetNameToken();
}
return null;
}
public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node)
=> node.GetAttributeLists();
public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) &&
xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName;
public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia)
{
if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia)
{
return documentationCommentTrivia.Content;
}
throw ExceptionUtilities.UnexpectedValue(trivia.Kind());
}
public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsPatternExpression);
public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right)
{
var isPatternExpression = (IsPatternExpressionSyntax)node;
left = isPatternExpression.Expression;
isToken = isPatternExpression.IsKeyword;
right = isPatternExpression.Pattern;
}
public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is PatternSyntax;
public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ConstantPattern);
public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.DeclarationPattern);
public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.RecursivePattern);
public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.VarPattern);
public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node)
=> ((ConstantPatternSyntax)node).Expression;
public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation)
{
var declarationPattern = (DeclarationPatternSyntax)node;
type = declarationPattern.Type;
designation = declarationPattern.Designation;
}
public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation)
{
var recursivePattern = (RecursivePatternSyntax)node;
type = recursivePattern.Type;
positionalPart = recursivePattern.PositionalPatternClause;
propertyPart = recursivePattern.PropertyPatternClause;
designation = recursivePattern.Designation;
}
public bool SupportsNotPattern(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove();
public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AndPattern);
public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryPatternSyntax;
public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.NotPattern);
public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.OrPattern);
public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParenthesizedPattern);
public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.TypePattern);
public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is UnaryPatternSyntax;
public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen)
{
var parenthesizedPattern = (ParenthesizedPatternSyntax)node;
openParen = parenthesizedPattern.OpenParenToken;
pattern = parenthesizedPattern.Pattern;
closeParen = parenthesizedPattern.CloseParenToken;
}
public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryPattern = (BinaryPatternSyntax)node;
left = binaryPattern.Left;
operatorToken = binaryPattern.OperatorToken;
right = binaryPattern.Right;
}
public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern)
{
var unaryPattern = (UnaryPatternSyntax)node;
operatorToken = unaryPattern.OperatorToken;
pattern = unaryPattern.Pattern;
}
public SyntaxNode GetTypeOfTypePattern(SyntaxNode node)
=> ((TypePatternSyntax)node).Type;
public void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken)
{
var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node;
stringStartToken = interpolatedStringExpression.StringStartToken;
contents = interpolatedStringExpression.Contents;
stringEndToken = interpolatedStringExpression.StringEndToken;
}
public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node)
=> node is InterpolatedStringExpressionSyntax interpolatedString &&
interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken);
#region IsXXX members
public bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is AnonymousFunctionExpressionSyntax;
public bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node is BaseNamespaceDeclarationSyntax;
public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryExpressionSyntax;
public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is LiteralExpressionSyntax;
public bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberAccessExpressionSyntax;
public bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node)
=> node is SimpleNameSyntax;
#endregion
#region GetPartsOfXXX members
public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryExpression = (BinaryExpressionSyntax)node;
left = binaryExpression.Left;
operatorToken = binaryExpression.OperatorToken;
right = binaryExpression.Right;
}
public void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members)
{
var compilationUnit = (CompilationUnitSyntax)node;
imports = compilationUnit.Usings;
attributeLists = compilationUnit.AttributeLists;
members = compilationUnit.Members;
}
public void GetPartsOfConditionalAccessExpression(
SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull)
{
var conditionalAccess = (ConditionalAccessExpressionSyntax)node;
expression = conditionalAccess.Expression;
operatorToken = conditionalAccess.OperatorToken;
whenNotNull = conditionalAccess.WhenNotNull;
}
public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse)
{
var conditionalExpression = (ConditionalExpressionSyntax)node;
condition = conditionalExpression.Condition;
whenTrue = conditionalExpression.WhenTrue;
whenFalse = conditionalExpression.WhenFalse;
}
public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList)
{
var invocation = (InvocationExpressionSyntax)node;
expression = invocation.Expression;
argumentList = invocation.ArgumentList;
}
public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name)
{
var memberAccess = (MemberAccessExpressionSyntax)node;
expression = memberAccess.Expression;
operatorToken = memberAccess.OperatorToken;
name = memberAccess.Name;
}
public void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members)
{
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)node;
name = namespaceDeclaration.Name;
imports = namespaceDeclaration.Usings;
members = namespaceDeclaration.Members;
}
public void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer)
{
var objectCreationExpression = (ObjectCreationExpressionSyntax)node;
type = objectCreationExpression.Type;
argumentList = objectCreationExpression.ArgumentList;
initializer = objectCreationExpression.Initializer;
}
public void GetPartsOfParenthesizedExpression(
SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen)
{
var parenthesizedExpression = (ParenthesizedExpressionSyntax)node;
openParen = parenthesizedExpression.OpenParenToken;
expression = parenthesizedExpression.Expression;
closeParen = parenthesizedExpression.CloseParenToken;
}
public void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand)
{
var prefixUnaryExpression = (PrefixUnaryExpressionSyntax)node;
operatorToken = prefixUnaryExpression.OperatorToken;
operand = prefixUnaryExpression.Operand;
}
public void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var qualifiedName = (QualifiedNameSyntax)node;
left = qualifiedName.Left;
operatorToken = qualifiedName.DotToken;
right = qualifiedName.Right;
}
#endregion
#region GetXXXOfYYY members
public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node)
=> ((AwaitExpressionSyntax)node).Expression;
public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node)
=> ((ThrowExpressionSyntax)node).Expression;
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.CSharp.LanguageServices
{
internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts
{
internal static readonly CSharpSyntaxFacts Instance = new();
protected CSharpSyntaxFacts()
{
}
public override bool IsCaseSensitive => true;
public override StringComparer StringComparer { get; } = StringComparer.Ordinal;
public override SyntaxTrivia ElasticMarker
=> SyntaxFactory.ElasticMarker;
public override SyntaxTrivia ElasticCarriageReturnLineFeed
=> SyntaxFactory.ElasticCarriageReturnLineFeed;
public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance;
public override bool SupportsIndexingInitializer(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6;
public override bool SupportsThrowExpression(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public override bool SupportsLocalFunctionDeclaration(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public override bool SupportsRecord(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9;
public override bool SupportsRecordStruct(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove();
public override SyntaxToken ParseToken(string text)
=> SyntaxFactory.ParseToken(text);
public override SyntaxTriviaList ParseLeadingTrivia(string text)
=> SyntaxFactory.ParseLeadingTrivia(text);
public override string EscapeIdentifier(string identifier)
{
var nullIndex = identifier.IndexOf('\0');
if (nullIndex >= 0)
{
identifier = identifier.Substring(0, nullIndex);
}
var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None;
return needsEscaping ? "@" + identifier : identifier;
}
public override bool IsVerbatimIdentifier(SyntaxToken token)
=> token.IsVerbatimIdentifier();
public override bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public override bool IsReservedKeyword(SyntaxToken token)
=> SyntaxFacts.IsReservedKeyword(token.Kind());
public override bool IsContextualKeyword(SyntaxToken token)
=> SyntaxFacts.IsContextualKeyword(token.Kind());
public override bool IsPreprocessorKeyword(SyntaxToken token)
=> SyntaxFacts.IsPreprocessorKeyword(token.Kind());
public override bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
=> syntaxTree.IsPreProcessorDirectiveContext(
position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
public override bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken)
{
if (syntaxTree == null)
{
return false;
}
return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public override bool IsDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is DirectiveTriviaSyntax;
public override bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info)
{
if (node is LineDirectiveTriviaSyntax lineDirective)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default;
return false;
}
public override bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsSimpleMemberAccessExpressionName();
}
public override bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node;
public override bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberBindingExpressionName();
}
[return: NotNullIfNotNull("node")]
public override SyntaxNode? GetStandaloneExpression(SyntaxNode? node)
=> node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node;
public override SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node)
=> node.GetRootConditionalAccessExpression();
public override bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is DeclarationExpressionSyntax;
public override bool IsAttributeName(SyntaxNode node)
=> SyntaxFacts.IsAttributeName(node);
public override bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node is ArgumentSyntax arg && arg.NameColon != null;
public override bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.CheckParent<NameColonSyntax>(p => p.Name == node);
public override SyntaxToken? GetNameOfParameter(SyntaxNode? node)
=> (node as ParameterSyntax)?.Identifier;
public override SyntaxNode? GetDefaultOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Default;
public override SyntaxNode? GetParameterList(SyntaxNode node)
=> node.GetParameterList();
public override bool IsParameterList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList);
public override SyntaxToken GetIdentifierOfGenericName(SyntaxNode node)
=> ((GenericNameSyntax)node).Identifier;
public override bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) &&
usingDirective.Name == node;
public override bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null;
public override void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name)
{
var usingDirective = (UsingDirectiveSyntax)node;
globalKeyword = usingDirective.GlobalKeyword;
alias = usingDirective.Alias!.Name.Identifier;
name = usingDirective.Name;
}
public override bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is ForEachVariableStatementSyntax;
public override bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node)
=> node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction();
public override Location GetDeconstructionReferenceLocation(SyntaxNode node)
{
return node switch
{
AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(),
ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(),
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
};
}
public override bool IsStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public override bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public override bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node)
{
if (node is BlockSyntax ||
node is ArrowExpressionClauseSyntax)
{
return node.Parent is BaseMethodDeclarationSyntax ||
node.Parent is AccessorDeclarationSyntax;
}
return false;
}
public override SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node)
=> ((ReturnStatementSyntax)node).Expression;
public override bool IsThisConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public override bool IsBaseConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public override bool IsQueryKeyword(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.FromKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.InKeyword:
return token.Parent is QueryClauseSyntax;
case SyntaxKind.ByKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.SelectKeyword:
return token.Parent is SelectOrGroupClauseSyntax;
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
return token.Parent is OrderingSyntax;
case SyntaxKind.IntoKeyword:
return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation);
default:
return false;
}
}
public override bool IsPredefinedType(SyntaxToken token)
=> TryGetPredefinedType(token, out _);
public override bool IsPredefinedType(SyntaxToken token, PredefinedType type)
=> TryGetPredefinedType(token, out var actualType) && actualType == type;
public override bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private static PredefinedType GetPredefinedType(SyntaxToken token)
{
return (SyntaxKind)token.RawKind switch
{
SyntaxKind.BoolKeyword => PredefinedType.Boolean,
SyntaxKind.ByteKeyword => PredefinedType.Byte,
SyntaxKind.SByteKeyword => PredefinedType.SByte,
SyntaxKind.IntKeyword => PredefinedType.Int32,
SyntaxKind.UIntKeyword => PredefinedType.UInt32,
SyntaxKind.ShortKeyword => PredefinedType.Int16,
SyntaxKind.UShortKeyword => PredefinedType.UInt16,
SyntaxKind.LongKeyword => PredefinedType.Int64,
SyntaxKind.ULongKeyword => PredefinedType.UInt64,
SyntaxKind.FloatKeyword => PredefinedType.Single,
SyntaxKind.DoubleKeyword => PredefinedType.Double,
SyntaxKind.DecimalKeyword => PredefinedType.Decimal,
SyntaxKind.StringKeyword => PredefinedType.String,
SyntaxKind.CharKeyword => PredefinedType.Char,
SyntaxKind.ObjectKeyword => PredefinedType.Object,
SyntaxKind.VoidKeyword => PredefinedType.Void,
_ => PredefinedType.None,
};
}
public override bool IsPredefinedOperator(SyntaxToken token)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None;
public override bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op;
public override bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private static PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanToken:
return PredefinedOperator.LessThan;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public override string GetText(int kind)
=> SyntaxFacts.GetText((SyntaxKind)kind);
public override bool IsIdentifierStartCharacter(char c)
=> SyntaxFacts.IsIdentifierStartCharacter(c);
public override bool IsIdentifierPartCharacter(char c)
=> SyntaxFacts.IsIdentifierPartCharacter(c);
public override bool IsIdentifierEscapeCharacter(char c)
=> c == '@';
public override bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public override bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public override bool IsTypeCharacter(char c) => false;
public override bool IsStartOfUnicodeEscapeSequence(char c)
=> c == '\\';
public override bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
return true;
default:
return false;
}
}
public override bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token)
=> token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken);
public override bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
// In the order by clause a comma might be bound to ThenBy or ThenByDescending
if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause))
{
return true;
}
return false;
}
public override bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is PostfixUnaryExpressionSyntax;
public override bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberBindingExpressionSyntax;
public override bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression;
public override void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity)
{
var simpleName = (SimpleNameSyntax)node;
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
public override bool LooksGeneric(SyntaxNode simpleName)
=> simpleName.IsKind(SyntaxKind.GenericName) ||
simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken;
public override SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node)
=> (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression;
public override SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node)
=> ((MemberBindingExpressionSyntax)node).Name;
public override SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget)
=> ((MemberAccessExpressionSyntax)node).Expression;
public override void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList)
{
var elementAccess = (ElementAccessExpressionSyntax)node;
expression = elementAccess.Expression;
argumentList = elementAccess.ArgumentList;
}
public override SyntaxNode GetExpressionOfInterpolation(SyntaxNode node)
=> ((InterpolationSyntax)node).Expression;
public override bool IsInStaticContext(SyntaxNode node)
=> node.IsInStaticContext();
public override bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node)
=> SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
public override bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.BaseList);
public override SyntaxNode GetExpressionOfArgument(SyntaxNode node)
=> ((ArgumentSyntax)node).Expression;
public override RefKind GetRefKindOfArgument(SyntaxNode node)
=> ((ArgumentSyntax)node).GetRefKind();
public override bool IsArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Argument);
public override bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node)
{
return node is ArgumentSyntax argument &&
argument.RefOrOutKeyword.Kind() == SyntaxKind.None &&
argument.NameColon == null;
}
public override bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsInConstantContext();
public override bool IsInConstructor(SyntaxNode node)
=> node.GetAncestor<ConstructorDeclarationSyntax>() != null;
public override bool IsUnsafeContext(SyntaxNode node)
=> node.IsUnsafeContext();
public override SyntaxNode GetNameOfAttribute(SyntaxNode node)
=> ((AttributeSyntax)node).Name;
public override bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier();
public override SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public override SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node)
=> throw ExceptionUtilities.Unreachable;
public override bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IdentifierName) &&
node.IsParentKind(SyntaxKind.NameColon) &&
node.Parent.IsParentKind(SyntaxKind.Subpattern);
public override bool IsPropertyPatternClause(SyntaxNode node)
=> node.Kind() == SyntaxKind.PropertyPatternClause;
public override bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> IsMemberInitializerNamedAssignmentIdentifier(node, out _);
public override bool IsMemberInitializerNamedAssignmentIdentifier(
[NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance)
{
initializedInstance = null;
if (node is IdentifierNameSyntax identifier &&
identifier.IsLeftSideOfAssignExpression())
{
if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression))
{
var withInitializer = identifier.Parent.GetRequiredParent();
initializedInstance = withInitializer.GetRequiredParent();
return true;
}
else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression))
{
var objectInitializer = identifier.Parent.GetRequiredParent();
if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax)
{
initializedInstance = objectInitializer.Parent;
return true;
}
else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment))
{
initializedInstance = assignment.Left;
return true;
}
}
}
return false;
}
public override bool IsElementAccessExpression(SyntaxNode? node)
=> node.IsKind(SyntaxKind.ElementAccessExpression);
[return: NotNullIfNotNull("node")]
public override SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false)
=> node.ConvertToSingleLine(useElasticTrivia);
public override bool IsIndexerMemberCRef(SyntaxNode? node)
=> node.IsKind(SyntaxKind.IndexerMemberCref);
public override SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (useFullSpan || node.Span.Contains(position))
{
var kind = node.Kind();
if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax))
{
return node;
}
}
node = node.Parent;
}
return null;
}
public override bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseMethodDeclarationSyntax ||
node is BasePropertyDeclarationSyntax ||
node is EnumMemberDeclarationSyntax ||
node is BaseFieldDeclarationSyntax;
}
public override bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseNamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
private const string dotToken = ".";
public override string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null)
{
if (node == null)
{
return string.Empty;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
// return type
var memberDeclaration = node as MemberDeclarationSyntax;
if ((options & DisplayNameOptions.IncludeType) != 0)
{
var type = memberDeclaration.GetMemberType();
if (type != null && !type.IsMissing)
{
builder.Append(type);
builder.Append(' ');
}
}
var names = ArrayBuilder<string?>.GetInstance();
// containing type(s)
var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent;
while (parent is TypeDeclarationSyntax)
{
names.Push(GetName(parent, options));
parent = parent.Parent;
}
// containing namespace(s) in source (if any)
if ((options & DisplayNameOptions.IncludeNamespaces) != 0)
{
while (parent is BaseNamespaceDeclarationSyntax)
{
names.Add(GetName(parent, options));
parent = parent.Parent;
}
}
while (!names.IsEmpty())
{
var name = names.Pop();
if (name != null)
{
builder.Append(name);
builder.Append(dotToken);
}
}
// name (including generic type parameters)
builder.Append(GetName(node, options));
// parameter list (if any)
if ((options & DisplayNameOptions.IncludeParameters) != 0)
{
builder.Append(memberDeclaration.GetParameterList());
}
return pooled.ToStringAndFree();
}
private static string? GetName(SyntaxNode node, DisplayNameOptions options)
{
const string missingTokenPlaceholder = "?";
switch (node.Kind())
{
case SyntaxKind.CompilationUnit:
return null;
case SyntaxKind.IdentifierName:
var identifier = ((IdentifierNameSyntax)node).Identifier;
return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text;
case SyntaxKind.IncompleteMember:
return missingTokenPlaceholder;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options);
}
string? name = null;
if (node is MemberDeclarationSyntax memberDeclaration)
{
if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration)
{
name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString();
}
else
{
var nameToken = memberDeclaration.GetNameToken();
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration)
{
name = "~" + name;
}
if ((options & DisplayNameOptions.IncludeTypeParameters) != 0)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList());
name = pooled.ToStringAndFree();
}
}
else
{
Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember);
name = "?";
}
}
}
else
{
if (node is VariableDeclaratorSyntax fieldDeclarator)
{
var nameToken = fieldDeclarator.Identifier;
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
}
}
}
Debug.Assert(name != null, "Unexpected node type " + node.Kind());
return name;
}
private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (var i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(", ");
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
}
}
public override List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: true, methodLevel: true);
return list;
}
public override List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: false, methodLevel: true);
return list;
}
public override SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration)
=> ((TypeDeclarationSyntax)typeDeclaration).Members;
private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel)
{
Debug.Assert(topLevel || methodLevel);
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (topLevel)
{
list.Add(member);
}
AppendMembers(member, list, topLevel, methodLevel);
continue;
}
if (methodLevel && IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public override TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default;
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default;
}
// TODO: currently we only support method for now
if (member is BaseMethodDeclarationSyntax method)
{
if (method.Body == null)
{
return default;
}
return GetBlockBodySpan(method.Body);
}
return default;
}
public override bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span)
{
switch (node)
{
case ConstructorDeclarationSyntax constructor:
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
case BaseMethodDeclarationSyntax method:
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
case BasePropertyDeclarationSyntax property:
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
case EnumMemberDeclarationSyntax @enum:
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
case BaseFieldDeclarationSyntax field:
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private static TextSpan GetBlockBodySpan(BlockSyntax body)
=> TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
public override SyntaxNode? TryGetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
if (parent is MemberAccessExpressionSyntax memberAccess)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is QualifiedNameSyntax qualifiedName)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
if (parent is ObjectCreationExpressionSyntax objectCreation)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// The inside of an interpolated string is treated as its own token so we
// need to force navigation to the parent expression syntax.
if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax)
{
node = parent;
break;
}
// If this node is not parented by a name, we're done.
if (!(parent is NameSyntax))
{
break;
}
node = parent;
}
if (node is VarPatternSyntax)
{
return node;
}
// Patterns are never bindable (though their constituent types/exprs may be).
return node is PatternSyntax ? null : node;
}
public override IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken)
{
if (root is not CompilationUnitSyntax compilationUnit)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
switch (member)
{
case ConstructorDeclarationSyntax constructor:
constructors.Add(constructor);
continue;
case BaseNamespaceDeclarationSyntax @namespace:
AppendConstructors(@namespace.Members, constructors, cancellationToken);
break;
case ClassDeclarationSyntax @class:
AppendConstructors(@class.Members, constructors, cancellationToken);
break;
case RecordDeclarationSyntax record:
AppendConstructors(record.Members, constructors, cancellationToken);
break;
case StructDeclarationSyntax @struct:
AppendConstructors(@struct.Members, constructors, cancellationToken);
break;
}
}
}
public override bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.openBrace;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default;
return false;
}
public override TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return trivia.FullSpan;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return default;
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return default;
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax branch)
{
return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default;
}
}
}
}
return default;
}
public override string GetNameForArgument(SyntaxNode? argument)
=> (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty;
public override string GetNameForAttributeArgument(SyntaxNode? argument)
=> (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty;
public override bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfDot();
public override SyntaxNode? GetRightSideOfDot(SyntaxNode? node)
{
return (node as QualifiedNameSyntax)?.Right ??
(node as MemberAccessExpressionSyntax)?.Name;
}
public override SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget)
{
return (node as QualifiedNameSyntax)?.Left ??
(node as MemberAccessExpressionSyntax)?.Expression;
}
public override bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier();
public override bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAssignExpression();
public override bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression();
public override bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression();
public override SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node)
=> ((AssignmentExpressionSyntax)node).Right;
public override bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) &&
anonObject.NameEquals == null;
public override bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostIncrementExpression) ||
node.IsParentKind(SyntaxKind.PreIncrementExpression);
public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostDecrementExpression) ||
node.IsParentKind(SyntaxKind.PreDecrementExpression);
public override bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node);
public override SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString)
=> ((InterpolatedStringExpressionSyntax)interpolatedString).Contents;
public override bool IsVerbatimStringLiteral(SyntaxToken token)
=> token.IsVerbatimStringLiteral();
public override bool IsNumericLiteral(SyntaxToken token)
=> token.Kind() == SyntaxKind.NumericLiteralToken;
public override SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode invocationExpression)
=> GetArgumentsOfArgumentList(((InvocationExpressionSyntax)invocationExpression).ArgumentList);
public override SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode objectCreationExpression)
=> ((BaseObjectCreationExpressionSyntax)objectCreationExpression).ArgumentList is { } argumentList
? GetArgumentsOfArgumentList(argumentList)
: default;
public override SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode argumentList)
=> ((BaseArgumentListSyntax)argumentList).Arguments;
public override bool IsRegularComment(SyntaxTrivia trivia)
=> trivia.IsRegularComment();
public override bool IsDocumentationComment(SyntaxTrivia trivia)
=> trivia.IsDocComment();
public override bool IsElastic(SyntaxTrivia trivia)
=> trivia.IsElastic();
public override bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes)
=> trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes);
public override bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia)
=> trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia;
public override bool IsDocumentationComment(SyntaxNode node)
=> SyntaxFacts.IsDocumentationCommentTrivia(node.Kind());
public override bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node)
{
return node.IsKind(SyntaxKind.UsingDirective) ||
node.IsKind(SyntaxKind.ExternAliasDirective);
}
public override bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword);
public override bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.ModuleKeyword);
private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget)
=> node.IsKind(SyntaxKind.Attribute) &&
node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) &&
attributeList.Target?.Identifier.Kind() == attributeTarget;
private static bool IsMemberDeclaration(SyntaxNode node)
{
// From the C# language spec:
// class-member-declaration:
// constant-declaration
// field-declaration
// method-declaration
// property-declaration
// event-declaration
// indexer-declaration
// operator-declaration
// constructor-declaration
// destructor-declaration
// static-constructor-declaration
// type-declaration
switch (node.Kind())
{
// Because fields declarations can define multiple symbols "public int a, b;"
// We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
case SyntaxKind.VariableDeclarator:
return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) ||
node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
return true;
default:
return false;
}
}
public override bool IsDeclaration(SyntaxNode node)
=> SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node);
public override bool IsTypeDeclaration(SyntaxNode node)
=> SyntaxFacts.IsTypeDeclaration(node.Kind());
public override bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement)
=> statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) &&
exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression);
public override void GetPartsOfAssignmentStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
GetPartsOfAssignmentExpressionOrStatement(
((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right);
}
public override void GetPartsOfAssignmentExpressionOrStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var expression = statement;
if (statement is ExpressionStatementSyntax expressionStatement)
{
expression = expressionStatement.Expression;
}
var assignment = (AssignmentExpressionSyntax)expression;
left = assignment.Left;
operatorToken = assignment.OperatorToken;
right = assignment.Right;
}
public override SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node)
=> ((SimpleNameSyntax)node).Identifier;
public override SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Identifier;
public override SyntaxToken GetIdentifierOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Identifier;
public override SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node)
=> node switch
{
BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier,
DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier,
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
public override SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node)
=> ((IdentifierNameSyntax)node).Identifier;
public override bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement)
{
return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains(
(VariableDeclaratorSyntax)declarator);
}
public override bool AreEquivalent(SyntaxToken token1, SyntaxToken token2)
=> SyntaxFactory.AreEquivalent(token1, token2);
public override bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2)
=> SyntaxFactory.AreEquivalent(node1, node2);
public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node)
=> ((InvocationExpressionSyntax)node).Expression;
public override bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node;
public override SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node)
=> ((ExpressionStatementSyntax)node).Expression;
public override bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsExpression);
[return: NotNullIfNotNull("node")]
public override SyntaxNode? WalkDownParentheses(SyntaxNode? node)
=> (node as ExpressionSyntax)?.WalkDownParentheses() ?? node;
public override void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen)
{
var tupleExpression = (TupleExpressionSyntax)node;
openParen = tupleExpression.OpenParenToken;
arguments = (SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments;
closeParen = tupleExpression.CloseParenToken;
}
public override bool IsPreprocessorDirective(SyntaxTrivia trivia)
=> SyntaxFacts.IsPreprocessorDirective(trivia.Kind());
public override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken)
=> token.ContainsInterleavedDirective(span, cancellationToken);
public override SyntaxTokenList GetModifiers(SyntaxNode? node)
=> node.GetModifiers();
public override SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers)
=> node.WithModifiers(modifiers);
public override SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node)
=> ((LocalDeclarationStatementSyntax)node).Declaration.Variables;
public override SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Initializer;
public override SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type;
public override SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node)
=> ((EqualsValueClauseSyntax?)node)?.Value;
public override bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block);
public override bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit);
public override IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node)
{
return node switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement),
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
}
public override SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode(node => IsExecutableBlock(node));
public override bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node)
=> IsExecutableBlock(node) || node.IsEmbeddedStatementOwner();
public override IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node)
{
if (IsExecutableBlock(node))
return GetExecutableBlockStatements(node);
else if (node.GetEmbeddedStatement() is { } embeddedStatement)
return ImmutableArray.Create<SyntaxNode>(embeddedStatement);
else
return ImmutableArray<SyntaxNode>.Empty;
}
public override bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public override bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public override void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression)
{
var cast = (CastExpressionSyntax)node;
type = cast.Type;
expression = cast.Expression;
}
public override SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member)
{
return member.GetNameToken();
}
return null;
}
public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node)
=> node.GetAttributeLists();
public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) &&
xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName;
public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia)
{
if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia)
{
return documentationCommentTrivia.Content;
}
throw ExceptionUtilities.UnexpectedValue(trivia.Kind());
}
public override bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsPatternExpression);
public override void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right)
{
var isPatternExpression = (IsPatternExpressionSyntax)node;
left = isPatternExpression.Expression;
isToken = isPatternExpression.IsKeyword;
right = isPatternExpression.Pattern;
}
public override bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is PatternSyntax;
public override bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ConstantPattern);
public override bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.DeclarationPattern);
public override bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.RecursivePattern);
public override bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.VarPattern);
public override SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node)
=> ((ConstantPatternSyntax)node).Expression;
public override void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation)
{
var declarationPattern = (DeclarationPatternSyntax)node;
type = declarationPattern.Type;
designation = declarationPattern.Designation;
}
public override void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation)
{
var recursivePattern = (RecursivePatternSyntax)node;
type = recursivePattern.Type;
positionalPart = recursivePattern.PositionalPatternClause;
propertyPart = recursivePattern.PropertyPatternClause;
designation = recursivePattern.Designation;
}
public override bool SupportsNotPattern(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove();
public override bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AndPattern);
public override bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryPatternSyntax;
public override bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.NotPattern);
public override bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.OrPattern);
public override bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParenthesizedPattern);
public override bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.TypePattern);
public override bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is UnaryPatternSyntax;
public override void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen)
{
var parenthesizedPattern = (ParenthesizedPatternSyntax)node;
openParen = parenthesizedPattern.OpenParenToken;
pattern = parenthesizedPattern.Pattern;
closeParen = parenthesizedPattern.CloseParenToken;
}
public override void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryPattern = (BinaryPatternSyntax)node;
left = binaryPattern.Left;
operatorToken = binaryPattern.OperatorToken;
right = binaryPattern.Right;
}
public override void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern)
{
var unaryPattern = (UnaryPatternSyntax)node;
operatorToken = unaryPattern.OperatorToken;
pattern = unaryPattern.Pattern;
}
public override SyntaxNode GetTypeOfTypePattern(SyntaxNode node)
=> ((TypePatternSyntax)node).Type;
public override void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken)
{
var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node;
stringStartToken = interpolatedStringExpression.StringStartToken;
contents = interpolatedStringExpression.Contents;
stringEndToken = interpolatedStringExpression.StringEndToken;
}
public override bool IsVerbatimInterpolatedStringExpression(SyntaxNode node)
=> node is InterpolatedStringExpressionSyntax interpolatedString &&
interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken);
#region IsXXX members
public override bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is AnonymousFunctionExpressionSyntax;
public override bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node is BaseNamespaceDeclarationSyntax;
public override bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryExpressionSyntax;
public override bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is LiteralExpressionSyntax;
public override bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberAccessExpressionSyntax;
public override bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node)
=> node is SimpleNameSyntax;
#endregion
#region GetPartsOfXXX members
public override void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryExpression = (BinaryExpressionSyntax)node;
left = binaryExpression.Left;
operatorToken = binaryExpression.OperatorToken;
right = binaryExpression.Right;
}
public override void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members)
{
var compilationUnit = (CompilationUnitSyntax)node;
imports = compilationUnit.Usings;
attributeLists = compilationUnit.AttributeLists;
members = compilationUnit.Members;
}
public override void GetPartsOfConditionalAccessExpression(
SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull)
{
var conditionalAccess = (ConditionalAccessExpressionSyntax)node;
expression = conditionalAccess.Expression;
operatorToken = conditionalAccess.OperatorToken;
whenNotNull = conditionalAccess.WhenNotNull;
}
public override void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse)
{
var conditionalExpression = (ConditionalExpressionSyntax)node;
condition = conditionalExpression.Condition;
whenTrue = conditionalExpression.WhenTrue;
whenFalse = conditionalExpression.WhenFalse;
}
public override void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList)
{
var invocation = (InvocationExpressionSyntax)node;
expression = invocation.Expression;
argumentList = invocation.ArgumentList;
}
public override void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name)
{
var memberAccess = (MemberAccessExpressionSyntax)node;
expression = memberAccess.Expression;
operatorToken = memberAccess.OperatorToken;
name = memberAccess.Name;
}
public override void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members)
{
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)node;
name = namespaceDeclaration.Name;
imports = namespaceDeclaration.Usings;
members = namespaceDeclaration.Members;
}
public override void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer)
{
var objectCreationExpression = (ObjectCreationExpressionSyntax)node;
type = objectCreationExpression.Type;
argumentList = objectCreationExpression.ArgumentList;
initializer = objectCreationExpression.Initializer;
}
public override void GetPartsOfParenthesizedExpression(
SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen)
{
var parenthesizedExpression = (ParenthesizedExpressionSyntax)node;
openParen = parenthesizedExpression.OpenParenToken;
expression = parenthesizedExpression.Expression;
closeParen = parenthesizedExpression.CloseParenToken;
}
public override void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand)
{
var prefixUnaryExpression = (PrefixUnaryExpressionSyntax)node;
operatorToken = prefixUnaryExpression.OperatorToken;
operand = prefixUnaryExpression.Operand;
}
public override void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var qualifiedName = (QualifiedNameSyntax)node;
left = qualifiedName.Left;
operatorToken = qualifiedName.DotToken;
right = qualifiedName.Right;
}
#endregion
#region GetXXXOfYYY members
public override SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node)
=> ((AwaitExpressionSyntax)node).Expression;
public override SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node)
=> ((ThrowExpressionSyntax)node).Expression;
#endregion
}
}
| 1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/AbstractSyntaxFacts.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal abstract class AbstractSyntaxFacts
{
public abstract ISyntaxKinds SyntaxKinds { get; }
protected AbstractSyntaxFacts()
{
}
public bool IsSingleLineCommentTrivia(SyntaxTrivia trivia)
=> SyntaxKinds.SingleLineCommentTrivia == trivia.RawKind;
public bool IsMultiLineCommentTrivia(SyntaxTrivia trivia)
=> SyntaxKinds.MultiLineCommentTrivia == trivia.RawKind;
public bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia)
=> SyntaxKinds.SingleLineDocCommentTrivia == trivia.RawKind;
public bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia)
=> SyntaxKinds.MultiLineDocCommentTrivia == trivia.RawKind;
public bool IsShebangDirectiveTrivia(SyntaxTrivia trivia)
=> SyntaxKinds.ShebangDirectiveTrivia == trivia.RawKind;
public abstract bool IsPreprocessorDirective(SyntaxTrivia trivia);
public abstract bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken);
public abstract SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode node);
public abstract bool IsParameterNameXmlElementSyntax(SyntaxNode node);
public abstract SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
public bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent?.RawKind == SyntaxKinds.IncompleteMember;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal abstract class AbstractSyntaxFacts : ISyntaxFacts
{
public abstract ISyntaxKinds SyntaxKinds { get; }
protected AbstractSyntaxFacts()
{
}
public abstract bool IsPreprocessorDirective(SyntaxTrivia trivia);
public abstract bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken);
public abstract SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node);
public abstract bool IsParameterNameXmlElementSyntax(SyntaxNode? node);
public abstract SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
public bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent?.RawKind == SyntaxKinds.IncompleteMember;
public abstract bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2);
public abstract bool AreEquivalent(SyntaxToken token1, SyntaxToken token2);
public abstract bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span);
public abstract bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsArgument([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsAttributeName(SyntaxNode node);
public abstract bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsBaseConstructorInitializer(SyntaxToken token);
public abstract bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsBindableToken(SyntaxToken token);
public abstract bool IsCaseSensitive { get; }
public abstract bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsContextualKeyword(SyntaxToken token);
public abstract bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsDeclaration(SyntaxNode node);
public abstract bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement);
public abstract bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsDirective([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsDocumentationComment(SyntaxNode node);
public abstract bool IsDocumentationComment(SyntaxTrivia trivia);
public abstract bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia);
public abstract bool IsElastic(SyntaxTrivia trivia);
public abstract bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken);
public abstract bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsIdentifierEscapeCharacter(char c);
public abstract bool IsIdentifierPartCharacter(char c);
public abstract bool IsIdentifierStartCharacter(char c);
public abstract bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsInConstructor(SyntaxNode node);
public abstract bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsInStaticContext(SyntaxNode node);
public abstract bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsLiteral(SyntaxToken token);
public abstract bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance);
public abstract bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsNumericLiteral(SyntaxToken token);
public abstract bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsOperator(SyntaxToken token);
public abstract bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsParameterList([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes);
public abstract bool IsPredefinedOperator(SyntaxToken token);
public abstract bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op);
public abstract bool IsPredefinedType(SyntaxToken token);
public abstract bool IsPredefinedType(SyntaxToken token, PredefinedType type);
public abstract bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
public abstract bool IsPreprocessorKeyword(SyntaxToken token);
public abstract bool IsPropertyPatternClause(SyntaxNode node);
public abstract bool IsQueryKeyword(SyntaxToken token);
public abstract bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsRegularComment(SyntaxTrivia trivia);
public abstract bool IsReservedKeyword(SyntaxToken token);
public abstract bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement);
public abstract bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsStartOfUnicodeEscapeSequence(char c);
public abstract bool IsStatement([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token);
public abstract bool IsThisConstructorInitializer(SyntaxToken token);
public abstract bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsTypeCharacter(char c);
public abstract bool IsTypeDeclaration(SyntaxNode node);
public abstract bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsUnsafeContext(SyntaxNode node);
public abstract bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsValidIdentifier(string identifier);
public abstract bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node);
public abstract bool IsVerbatimIdentifier(string identifier);
public abstract bool IsVerbatimIdentifier(SyntaxToken token);
public abstract bool IsVerbatimInterpolatedStringExpression(SyntaxNode node);
public abstract bool IsVerbatimStringLiteral(SyntaxToken token);
public abstract bool LooksGeneric(SyntaxNode simpleName);
public abstract bool SupportsIndexingInitializer(ParseOptions options);
public abstract bool SupportsLocalFunctionDeclaration(ParseOptions options);
public abstract bool SupportsNotPattern(ParseOptions options);
public abstract bool SupportsRecord(ParseOptions options);
public abstract bool SupportsRecordStruct(ParseOptions options);
public abstract bool SupportsThrowExpression(ParseOptions options);
public abstract bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace);
public abstract bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info);
public abstract bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op);
public abstract bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type);
public abstract IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken);
public abstract IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node);
public abstract IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node);
public abstract List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root);
public abstract List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root);
public abstract Location GetDeconstructionReferenceLocation(SyntaxNode node);
public abstract RefKind GetRefKindOfArgument(SyntaxNode node);
public abstract SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node);
public abstract SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node);
public abstract SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node);
public abstract SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node);
public abstract string EscapeIdentifier(string identifier);
public abstract string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null);
public abstract string GetNameForArgument(SyntaxNode? argument);
public abstract string GetNameForAttributeArgument(SyntaxNode? argument);
public abstract string GetText(int kind);
public abstract StringComparer StringComparer { get; }
public abstract SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString);
public abstract SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration);
public abstract SyntaxNode GetExpressionOfArgument(SyntaxNode node);
public abstract SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node);
public abstract SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node);
public abstract SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node);
public abstract SyntaxNode GetExpressionOfInterpolation(SyntaxNode node);
public abstract SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node);
public abstract SyntaxNode GetNameOfAttribute(SyntaxNode node);
public abstract SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node);
public abstract SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node);
public abstract SyntaxNode GetTypeOfTypePattern(SyntaxNode node);
public abstract SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node);
public abstract SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes);
public abstract SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true);
public abstract SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position);
public abstract SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node);
public abstract SyntaxNode? GetDefaultOfParameter(SyntaxNode node);
public abstract SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false);
public abstract SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node);
public abstract SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node);
public abstract SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false);
public abstract SyntaxNode? GetParameterList(SyntaxNode node);
public abstract SyntaxNode? GetRightSideOfDot(SyntaxNode? node);
public abstract SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node);
public abstract SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node);
public abstract SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node);
public abstract SyntaxNode? TryGetBindableParent(SyntaxToken token);
public abstract SyntaxToken GetIdentifierOfGenericName(SyntaxNode node);
public abstract SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node);
public abstract SyntaxToken GetIdentifierOfParameter(SyntaxNode node);
public abstract SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node);
public abstract SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node);
public abstract SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node);
public abstract SyntaxToken ParseToken(string text);
public abstract SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token);
public abstract SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node);
public abstract SyntaxTokenList GetModifiers(SyntaxNode? node);
public abstract SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
public abstract SyntaxTrivia ElasticMarker { get; }
public abstract SyntaxTriviaList ParseLeadingTrivia(string text);
public abstract TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken);
public abstract TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node);
public abstract void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity);
public abstract void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
public abstract void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
public abstract void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members);
public abstract void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
public abstract void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
public abstract void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression);
public abstract void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members);
public abstract void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull);
public abstract void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse);
public abstract void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation);
public abstract void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList);
public abstract void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken);
public abstract void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList);
public abstract void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right);
public abstract void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name);
public abstract void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer);
public abstract void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen);
public abstract void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen);
public abstract void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand);
public abstract void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right);
public abstract void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation);
public abstract void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode;
public abstract void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern);
public abstract void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name);
[return: NotNullIfNotNull("node")]
public abstract SyntaxNode? GetStandaloneExpression(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
public abstract SyntaxNode? WalkDownParentheses(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
public abstract SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false);
[return: NotNullIfNotNull("node")]
public abstract SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers);
}
}
| 1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
/// <summary>
/// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion.
/// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform
/// fashion over the languages. Helpers in this type should only be one of the following forms:
/// <list type="bullet">
/// <item>
/// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that
/// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking'
/// methods should never fail. For non leaf node types this should be implemented as a typecheck ('is' in C#, 'typeof ... is'
/// in VB). For leaf nodes, this should be implemented by deffering to <see cref="ISyntaxKinds"/> to check against the
/// raw kind of the node.
/// </item>
/// <item>
/// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs
/// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the
/// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)'
/// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for.
/// For nodes that only have a single child, 'GetPartsOfXXX' is not not needed and can be replaced with the easier to use
/// 'GetXXXOfYYY' to get that single child.
/// </item>
/// <item>
/// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For
/// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and
/// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for.
/// For nodes that only have a single child, these functions can stay here. For nodes with multiple children, these should migrate
/// to <see cref="ISyntaxFactsExtensions"/> and be built off of 'GetPartsOfXXX'.
/// </item>
/// <item>
/// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example,
/// if certain constructs (like 'patterns') are supported in that language or not.
/// </item>
/// </list>
///
/// <para>Importantly, avoid:</para>
///
/// <list type="bullet">
/// <item>
/// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName
/// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context).
/// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right
/// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts).
/// </item>
/// <item>
/// Functions which are effectively specific to a single feature are are just trying to find a place to place complex
/// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position
/// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of
/// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in
/// its own dedicated service.
/// </item>
/// <item>
/// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or
/// some other feature specific service.
/// </item>
/// <item>
/// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'.
/// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle
/// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs
/// to creep in.
/// </item>
/// <item>
/// Abbreviating or otherwise changing the names that C# and VB share here. For example use 'ObjectCreationExpression'
/// not 'ObjectCreation'. This prevents accidental duplication and keeps consistency with all members.
/// </item>
/// </list>
/// </summary>
/// <remarks>
/// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either
/// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service
/// for that purpose if needed by multiple features.
/// </remarks>
internal interface ISyntaxFacts
{
bool IsCaseSensitive { get; }
StringComparer StringComparer { get; }
SyntaxTrivia ElasticMarker { get; }
SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
ISyntaxKinds SyntaxKinds { get; }
bool SupportsIndexingInitializer(ParseOptions options);
bool SupportsLocalFunctionDeclaration(ParseOptions options);
bool SupportsNotPattern(ParseOptions options);
bool SupportsRecord(ParseOptions options);
bool SupportsRecordStruct(ParseOptions options);
bool SupportsThrowExpression(ParseOptions options);
SyntaxToken ParseToken(string text);
SyntaxTriviaList ParseLeadingTrivia(string text);
string EscapeIdentifier(string identifier);
bool IsVerbatimIdentifier(SyntaxToken token);
bool IsOperator(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token, PredefinedType type);
bool IsPredefinedOperator(SyntaxToken token);
bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op);
/// <summary>
/// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a
/// identifier that is always treated as being a special keyword, regardless of where it is
/// found in the token stream. Examples of this are tokens like <see langword="class"/> and
/// <see langword="Class"/> in C# and VB respectively.
///
/// Importantly, this does *not* include contextual keywords. If contextual keywords are
/// important for your scenario, use <see cref="IsContextualKeyword"/> or <see
/// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using
/// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know
/// if this is effectively any identifier in the language, regardless of whether the language
/// is treating it as a keyword or not.
/// </summary>
bool IsReservedKeyword(SyntaxToken token);
/// <summary>
/// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A
/// 'contextual' keyword is a identifier that is only treated as being a special keyword in
/// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a
/// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see
/// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not*
/// 'contextual' keywords. This is because they are not treated as keywords depending on
/// the syntactic context around them. Instead, the language always treats them identifiers
/// that have special *semantic* meaning if they end up not binding to an existing symbol.
///
/// Importantly, if <paramref name="token"/> is not in the syntactic construct where the
/// language thinks an identifier should be contextually treated as a keyword, then this
/// will return <see langword="false"/>.
///
/// Or, in other words, the parser must be able to identify these cases in order to be a
/// contextual keyword. If identification happens afterwards, it's not contextual.
/// </summary>
bool IsContextualKeyword(SyntaxToken token);
/// <summary>
/// The set of identifiers that have special meaning directly after the `#` token in a
/// preprocessor directive. For example `if` or `pragma`.
/// </summary>
bool IsPreprocessorKeyword(SyntaxToken token);
bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
bool IsLiteral(SyntaxToken token);
bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token);
bool IsNumericLiteral(SyntaxToken token);
bool IsVerbatimStringLiteral(SyntaxToken token);
bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaration(SyntaxNode node);
bool IsTypeDeclaration(SyntaxNode node);
bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsRegularComment(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxTrivia trivia);
bool IsElastic(SyntaxTrivia trivia);
bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes);
bool IsSingleLineCommentTrivia(SyntaxTrivia trivia);
bool IsMultiLineCommentTrivia(SyntaxTrivia trivia);
bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia);
bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia);
bool IsShebangDirectiveTrivia(SyntaxTrivia trivia);
bool IsPreprocessorDirective(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxNode node);
string GetText(int kind);
bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken);
bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type);
bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op);
bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info);
bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode;
void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken);
bool IsVerbatimInterpolatedStringExpression(SyntaxNode node);
// Left side of = assignment.
bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement);
void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
// Left side of any assignment (for example = or ??= or *= or += )
bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node);
// Left side of compound assignment (for example ??= or *= or += )
bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node);
bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightSideOfDot(SyntaxNode? node);
/// <summary>
/// Get the node on the left side of the dot if given a dotted expression.
/// </summary>
/// <param name="allowImplicitTarget">
/// In VB, we have a member access expression with a null expression, this may be one of the
/// following forms:
/// 1) new With { .a = 1, .b = .a .a refers to the anonymous type
/// 2) With obj : .m .m refers to the obj type
/// 3) new T() With { .a = 1, .b = .a 'a refers to the T type
/// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null.
/// This parameter has no affect on C# node.
/// </param>
SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false);
bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
[return: NotNullIfNotNull("node")]
SyntaxNode? GetStandaloneExpression(SyntaxNode? node);
/// <summary>
/// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works
/// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in
/// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of
/// a conditional access, and commonly represents the full standalone expression that can be operated on
/// atomically.
/// </summary>
SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node);
/// <summary>
/// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/>
/// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/>
/// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed
/// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this
/// may return the expression in the surrounding With-statement.
/// </summary>
SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false);
SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node);
SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node);
bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetDefaultOfParameter(SyntaxNode node);
SyntaxNode? GetParameterList(SyntaxNode node);
bool IsParameterList([NotNullWhen(true)] SyntaxNode? node);
bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia);
void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList);
SyntaxNode GetExpressionOfArgument(SyntaxNode node);
SyntaxNode GetExpressionOfInterpolation(SyntaxNode node);
SyntaxNode GetNameOfAttribute(SyntaxNode node);
bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken GetIdentifierOfGenericName(SyntaxNode node);
SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node);
SyntaxToken GetIdentifierOfParameter(SyntaxNode node);
SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node);
SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node);
SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node);
SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node);
/// <summary>
/// True if this is an argument with just an expression and nothing else (i.e. no ref/out,
/// no named params, no omitted args).
/// </summary>
bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsArgument([NotNullWhen(true)] SyntaxNode? node);
RefKind GetRefKindOfArgument(SyntaxNode node);
void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity);
bool LooksGeneric(SyntaxNode simpleName);
SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node);
bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node);
bool IsAttributeName(SyntaxNode node);
// Violation. Doesn't correspond to any shared structure for vb/c#
SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node);
bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance);
bool IsDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Returns true for nodes that represent the body of a method.
///
/// For VB this will be
/// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator
/// bodies as well as accessor bodies. It will not be true for things like sub() function()
/// lambdas.
///
/// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a
/// method/constructor/deconstructor/operator/accessor. It will not be included for local
/// functions.
/// </summary>
bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement);
SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node);
SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node);
bool IsThisConstructorInitializer(SyntaxToken token);
bool IsBaseConstructorInitializer(SyntaxToken token);
bool IsQueryKeyword(SyntaxToken token);
bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node);
bool IsIdentifierStartCharacter(char c);
bool IsIdentifierPartCharacter(char c);
bool IsIdentifierEscapeCharacter(char c);
bool IsStartOfUnicodeEscapeSequence(char c);
bool IsValidIdentifier(string identifier);
bool IsVerbatimIdentifier(string identifier);
/// <summary>
/// Returns true if the given character is a character which may be included in an
/// identifier to specify the type of a variable.
/// </summary>
bool IsTypeCharacter(char c);
// Violation. This is a feature level API for QuickInfo.
bool IsBindableToken(SyntaxToken token);
bool IsInStaticContext(SyntaxNode node);
bool IsUnsafeContext(SyntaxNode node);
bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstructor(SyntaxNode node);
bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node);
bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node);
bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax.
/// </summary>
bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax.
/// In VB, this includes all block statements such as a MultiLineIfBlockSyntax.
/// </summary>
bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node);
// Violation. This should return a SyntaxList
IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node);
// Violation. This is a feature level API.
SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes);
/// <summary>
/// A node that can host a list of statements or a single statement. In addition to
/// every "executable block", this also includes C# embedded statement owners.
/// </summary>
// Violation. This is a feature level API.
bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node);
// Violation. This is a feature level API.
IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node);
bool AreEquivalent(SyntaxToken token1, SyntaxToken token2);
bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2);
string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null);
// Violation. This is a feature level API. How 'position' relates to 'containment' is not defined.
SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position);
SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true);
SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
SyntaxNode? WalkDownParentheses(SyntaxNode? node);
// Violation. This is a feature level API.
[return: NotNullIfNotNull("node")]
SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false);
// Violation. This is a feature level API.
List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root);
// Violation. This is a feature level API.
List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root);
SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration);
// Violation. This is a feature level API.
bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span);
// Violation. This is a feature level API.
TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body
/// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be
/// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns
/// an empty <see cref="TextSpan"/> at position 0.
/// </summary>
// Violation. This is a feature level API.
TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node);
/// <summary>
/// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find
/// All References. For example, if the token is part of the type of an object creation, the parenting object
/// creation expression is returned so that binding will return constructor symbols.
/// </summary>
// Violation. This is a feature level API.
SyntaxNode? TryGetBindableParent(SyntaxToken token);
// Violation. This is a feature level API.
IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken);
// Violation. This is a feature level API.
bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of
/// that arguments name.
/// </summary>
// Violation. This is a feature level API.
string GetNameForArgument(SyntaxNode? argument);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of
/// that arguments name.
/// </summary>
// Violation. This is a feature level API.
string GetNameForAttributeArgument(SyntaxNode? argument);
bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node);
bool IsPropertyPatternClause(SyntaxNode node);
bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node);
SyntaxNode GetTypeOfTypePattern(SyntaxNode node);
void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen);
void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation);
void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation);
void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern);
bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken);
SyntaxTokenList GetModifiers(SyntaxNode? node);
// Violation. WithXXX methods should not be here, but should be in SyntaxGenerator.
[return: NotNullIfNotNull("node")]
SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers);
// Violation. This is a feature level API.
Location GetDeconstructionReferenceLocation(SyntaxNode node);
// Violation. This is a feature level API.
SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token);
bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node);
SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
#region IsXXX members
bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node);
#endregion
#region GetPartsOfXXX members
void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members);
void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression);
void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members);
void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull);
void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse);
void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList);
void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right);
void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name);
void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer);
void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen);
void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand);
void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right);
void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name);
#endregion
#region GetXXXOfYYYMembers
// note: this is only for nodes that have a single child nodes. If a node has multiple child nodes, then
// ISyntaxFacts should have a GetPartsOfXXX helper instead, and GetXXXOfYYY should be built off of that
// inside ISyntaxFactsExtensions
SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node);
SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node);
SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node);
SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node);
SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node);
#endregion
}
[Flags]
internal enum DisplayNameOptions
{
None = 0,
IncludeMemberKeyword = 1,
IncludeNamespaces = 1 << 1,
IncludeParameters = 1 << 2,
IncludeType = 1 << 3,
IncludeTypeParameters = 1 << 4
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
/// <summary>
/// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion.
/// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform
/// fashion over the languages. Helpers in this type should only be one of the following forms:
/// <list type="bullet">
/// <item>
/// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that
/// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking'
/// methods should never fail. For non leaf node types this should be implemented as a typecheck ('is' in C#, 'typeof ... is'
/// in VB). For leaf nodes, this should be implemented by deffering to <see cref="ISyntaxKinds"/> to check against the
/// raw kind of the node.
/// </item>
/// <item>
/// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs
/// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the
/// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)'
/// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for.
/// For nodes that only have a single child, 'GetPartsOfXXX' is not not needed and can be replaced with the easier to use
/// 'GetXXXOfYYY' to get that single child.
/// </item>
/// <item>
/// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For
/// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and
/// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for.
/// For nodes that only have a single child, these functions can stay here. For nodes with multiple children, these should migrate
/// to <see cref="ISyntaxFactsExtensions"/> and be built off of 'GetPartsOfXXX'.
/// </item>
/// <item>
/// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example,
/// if certain constructs (like 'patterns') are supported in that language or not.
/// </item>
/// </list>
///
/// <para>Importantly, avoid:</para>
///
/// <list type="bullet">
/// <item>
/// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName
/// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context).
/// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right
/// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts).
/// </item>
/// <item>
/// Functions which are effectively specific to a single feature are are just trying to find a place to place complex
/// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position
/// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of
/// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in
/// its own dedicated service.
/// </item>
/// <item>
/// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or
/// some other feature specific service.
/// </item>
/// <item>
/// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'.
/// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle
/// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs
/// to creep in.
/// </item>
/// <item>
/// Abbreviating or otherwise changing the names that C# and VB share here. For example use 'ObjectCreationExpression'
/// not 'ObjectCreation'. This prevents accidental duplication and keeps consistency with all members.
/// </item>
/// </list>
/// </summary>
/// <remarks>
/// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either
/// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service
/// for that purpose if needed by multiple features.
/// </remarks>
internal interface ISyntaxFacts
{
bool IsCaseSensitive { get; }
StringComparer StringComparer { get; }
SyntaxTrivia ElasticMarker { get; }
SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
ISyntaxKinds SyntaxKinds { get; }
bool SupportsIndexingInitializer(ParseOptions options);
bool SupportsLocalFunctionDeclaration(ParseOptions options);
bool SupportsNotPattern(ParseOptions options);
bool SupportsRecord(ParseOptions options);
bool SupportsRecordStruct(ParseOptions options);
bool SupportsThrowExpression(ParseOptions options);
SyntaxToken ParseToken(string text);
SyntaxTriviaList ParseLeadingTrivia(string text);
string EscapeIdentifier(string identifier);
bool IsVerbatimIdentifier(SyntaxToken token);
bool IsOperator(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token, PredefinedType type);
bool IsPredefinedOperator(SyntaxToken token);
bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op);
/// <summary>
/// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a
/// identifier that is always treated as being a special keyword, regardless of where it is
/// found in the token stream. Examples of this are tokens like <see langword="class"/> and
/// <see langword="Class"/> in C# and VB respectively.
///
/// Importantly, this does *not* include contextual keywords. If contextual keywords are
/// important for your scenario, use <see cref="IsContextualKeyword"/> or <see
/// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using
/// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know
/// if this is effectively any identifier in the language, regardless of whether the language
/// is treating it as a keyword or not.
/// </summary>
bool IsReservedKeyword(SyntaxToken token);
/// <summary>
/// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A
/// 'contextual' keyword is a identifier that is only treated as being a special keyword in
/// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a
/// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see
/// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not*
/// 'contextual' keywords. This is because they are not treated as keywords depending on
/// the syntactic context around them. Instead, the language always treats them identifiers
/// that have special *semantic* meaning if they end up not binding to an existing symbol.
///
/// Importantly, if <paramref name="token"/> is not in the syntactic construct where the
/// language thinks an identifier should be contextually treated as a keyword, then this
/// will return <see langword="false"/>.
///
/// Or, in other words, the parser must be able to identify these cases in order to be a
/// contextual keyword. If identification happens afterwards, it's not contextual.
/// </summary>
bool IsContextualKeyword(SyntaxToken token);
/// <summary>
/// The set of identifiers that have special meaning directly after the `#` token in a
/// preprocessor directive. For example `if` or `pragma`.
/// </summary>
bool IsPreprocessorKeyword(SyntaxToken token);
bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
bool IsLiteral(SyntaxToken token);
bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token);
bool IsNumericLiteral(SyntaxToken token);
bool IsVerbatimStringLiteral(SyntaxToken token);
bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaration(SyntaxNode node);
bool IsTypeDeclaration(SyntaxNode node);
bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsRegularComment(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxTrivia trivia);
bool IsElastic(SyntaxTrivia trivia);
bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes);
bool IsPreprocessorDirective(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxNode node);
string GetText(int kind);
bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken);
bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type);
bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op);
bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info);
bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode;
void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken);
bool IsVerbatimInterpolatedStringExpression(SyntaxNode node);
// Left side of = assignment.
bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement);
void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
// Left side of any assignment (for example = or ??= or *= or += )
bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node);
// Left side of compound assignment (for example ??= or *= or += )
bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node);
bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightSideOfDot(SyntaxNode? node);
/// <summary>
/// Get the node on the left side of the dot if given a dotted expression.
/// </summary>
/// <param name="allowImplicitTarget">
/// In VB, we have a member access expression with a null expression, this may be one of the
/// following forms:
/// 1) new With { .a = 1, .b = .a .a refers to the anonymous type
/// 2) With obj : .m .m refers to the obj type
/// 3) new T() With { .a = 1, .b = .a 'a refers to the T type
/// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null.
/// This parameter has no affect on C# node.
/// </param>
SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false);
bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
[return: NotNullIfNotNull("node")]
SyntaxNode? GetStandaloneExpression(SyntaxNode? node);
/// <summary>
/// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works
/// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in
/// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of
/// a conditional access, and commonly represents the full standalone expression that can be operated on
/// atomically.
/// </summary>
SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node);
/// <summary>
/// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/>
/// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/>
/// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed
/// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this
/// may return the expression in the surrounding With-statement.
/// </summary>
SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false);
SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node);
SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node);
bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetDefaultOfParameter(SyntaxNode node);
SyntaxNode? GetParameterList(SyntaxNode node);
bool IsParameterList([NotNullWhen(true)] SyntaxNode? node);
bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia);
void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList);
SyntaxNode GetExpressionOfArgument(SyntaxNode node);
SyntaxNode GetExpressionOfInterpolation(SyntaxNode node);
SyntaxNode GetNameOfAttribute(SyntaxNode node);
bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken GetIdentifierOfGenericName(SyntaxNode node);
SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node);
SyntaxToken GetIdentifierOfParameter(SyntaxNode node);
SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node);
SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node);
SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node);
SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node);
/// <summary>
/// True if this is an argument with just an expression and nothing else (i.e. no ref/out,
/// no named params, no omitted args).
/// </summary>
bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsArgument([NotNullWhen(true)] SyntaxNode? node);
RefKind GetRefKindOfArgument(SyntaxNode node);
void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity);
bool LooksGeneric(SyntaxNode simpleName);
SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node);
bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node);
bool IsAttributeName(SyntaxNode node);
// Violation. Doesn't correspond to any shared structure for vb/c#
SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node);
bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance);
bool IsDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Returns true for nodes that represent the body of a method.
///
/// For VB this will be
/// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator
/// bodies as well as accessor bodies. It will not be true for things like sub() function()
/// lambdas.
///
/// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a
/// method/constructor/deconstructor/operator/accessor. It will not be included for local
/// functions.
/// </summary>
bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement);
SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node);
SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node);
bool IsThisConstructorInitializer(SyntaxToken token);
bool IsBaseConstructorInitializer(SyntaxToken token);
bool IsQueryKeyword(SyntaxToken token);
bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node);
bool IsIdentifierStartCharacter(char c);
bool IsIdentifierPartCharacter(char c);
bool IsIdentifierEscapeCharacter(char c);
bool IsStartOfUnicodeEscapeSequence(char c);
bool IsValidIdentifier(string identifier);
bool IsVerbatimIdentifier(string identifier);
/// <summary>
/// Returns true if the given character is a character which may be included in an
/// identifier to specify the type of a variable.
/// </summary>
bool IsTypeCharacter(char c);
// Violation. This is a feature level API for QuickInfo.
bool IsBindableToken(SyntaxToken token);
bool IsInStaticContext(SyntaxNode node);
bool IsUnsafeContext(SyntaxNode node);
bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstructor(SyntaxNode node);
bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node);
bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node);
bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax.
/// </summary>
bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax.
/// In VB, this includes all block statements such as a MultiLineIfBlockSyntax.
/// </summary>
bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node);
// Violation. This should return a SyntaxList
IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node);
// Violation. This is a feature level API.
SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes);
/// <summary>
/// A node that can host a list of statements or a single statement. In addition to
/// every "executable block", this also includes C# embedded statement owners.
/// </summary>
// Violation. This is a feature level API.
bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node);
// Violation. This is a feature level API.
IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node);
bool AreEquivalent(SyntaxToken token1, SyntaxToken token2);
bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2);
string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null);
// Violation. This is a feature level API. How 'position' relates to 'containment' is not defined.
SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position);
SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true);
SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
SyntaxNode? WalkDownParentheses(SyntaxNode? node);
// Violation. This is a feature level API.
[return: NotNullIfNotNull("node")]
SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false);
// Violation. This is a feature level API.
List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root);
// Violation. This is a feature level API.
List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root);
SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration);
// Violation. This is a feature level API.
bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span);
// Violation. This is a feature level API.
TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body
/// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be
/// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns
/// an empty <see cref="TextSpan"/> at position 0.
/// </summary>
// Violation. This is a feature level API.
TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node);
/// <summary>
/// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find
/// All References. For example, if the token is part of the type of an object creation, the parenting object
/// creation expression is returned so that binding will return constructor symbols.
/// </summary>
// Violation. This is a feature level API.
SyntaxNode? TryGetBindableParent(SyntaxToken token);
// Violation. This is a feature level API.
IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken);
// Violation. This is a feature level API.
bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of
/// that arguments name.
/// </summary>
// Violation. This is a feature level API.
string GetNameForArgument(SyntaxNode? argument);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of
/// that arguments name.
/// </summary>
// Violation. This is a feature level API.
string GetNameForAttributeArgument(SyntaxNode? argument);
bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node);
bool IsPropertyPatternClause(SyntaxNode node);
bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node);
SyntaxNode GetTypeOfTypePattern(SyntaxNode node);
void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen);
void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation);
void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation);
void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern);
bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken);
SyntaxTokenList GetModifiers(SyntaxNode? node);
// Violation. WithXXX methods should not be here, but should be in SyntaxGenerator.
[return: NotNullIfNotNull("node")]
SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers);
// Violation. This is a feature level API.
Location GetDeconstructionReferenceLocation(SyntaxNode node);
// Violation. This is a feature level API.
SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token);
bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node);
SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
#region IsXXX members
bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node);
#endregion
#region GetPartsOfXXX members
void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members);
void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression);
void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members);
void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull);
void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse);
void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList);
void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right);
void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name);
void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer);
void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen);
void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand);
void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right);
void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name);
#endregion
#region GetXXXOfYYYMembers
// note: this is only for nodes that have a single child nodes. If a node has multiple child nodes, then
// ISyntaxFacts should have a GetPartsOfXXX helper instead, and GetXXXOfYYY should be built off of that
// inside ISyntaxFactsExtensions
SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node);
SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node);
SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node);
SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node);
SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node);
#endregion
}
[Flags]
internal enum DisplayNameOptions
{
None = 0,
IncludeMemberKeyword = 1,
IncludeNamespaces = 1 << 1,
IncludeParameters = 1 << 2,
IncludeType = 1 << 3,
IncludeTypeParameters = 1 << 4
}
}
| 1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFactsExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal static class ISyntaxFactsExtensions
{
private static readonly ObjectPool<Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)>> s_stackPool
= SharedPools.Default<Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)>>();
public static bool IsOnSingleLine(this ISyntaxFacts syntaxFacts, SyntaxNode node, bool fullSpan)
{
// The stack logic assumes the initial node is not null
Contract.ThrowIfNull(node);
// Use an actual Stack so we can write out deeply recursive structures without overflowing.
// Note: algorithm is taken from GreenNode.WriteTo.
//
// General approach is that we recurse down the nodes, using a real stack object to
// keep track of what node we're on. If full-span is true we'll examine all tokens
// and all the trivia on each token. If full-span is false we'll examine all tokens
// but we'll ignore the leading trivia on the very first trivia and the trailing trivia
// on the very last token.
var stack = s_stackPool.Allocate();
stack.Push((node, leading: fullSpan, trailing: fullSpan));
var result = IsOnSingleLine(syntaxFacts, stack);
s_stackPool.ClearAndFree(stack);
return result;
}
private static bool IsOnSingleLine(
ISyntaxFacts syntaxFacts, Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)> stack)
{
while (stack.Count > 0)
{
var (currentNodeOrToken, currentLeading, currentTrailing) = stack.Pop();
if (currentNodeOrToken.IsToken)
{
// If this token isn't on a single line, then the original node definitely
// isn't on a single line.
if (!IsOnSingleLine(syntaxFacts, currentNodeOrToken.AsToken(), currentLeading, currentTrailing))
return false;
}
else
{
var currentNode = currentNodeOrToken.AsNode()!;
var childNodesAndTokens = currentNode.ChildNodesAndTokens();
var childCount = childNodesAndTokens.Count;
// Walk the children of this node in reverse, putting on the stack to process.
// This way we process the children in the actual child-order they are in for
// this node.
var index = 0;
foreach (var child in childNodesAndTokens.Reverse())
{
// Since we're walking the children in reverse, if we're on hte 0th item,
// that's the last child.
var last = index == 0;
// Once we get all the way to the end of the reversed list, we're actually
// on the first.
var first = index == childCount - 1;
// We want the leading trivia if we've asked for it, or if we're not the first
// token being processed. We want the trailing trivia if we've asked for it,
// or if we're not the last token being processed.
stack.Push((child, currentLeading | !first, currentTrailing | !last));
index++;
}
}
}
// All tokens were on a single line. This node is on a single line.
return true;
}
private static bool IsOnSingleLine(ISyntaxFacts syntaxFacts, SyntaxToken token, bool leading, bool trailing)
{
// If any of our trivia is not on a single line, then we're not on a single line.
if (!IsOnSingleLine(syntaxFacts, token.LeadingTrivia, leading) ||
!IsOnSingleLine(syntaxFacts, token.TrailingTrivia, trailing))
{
return false;
}
// Only string literals can span multiple lines. Only need to check those.
if (syntaxFacts.SyntaxKinds.StringLiteralToken == token.RawKind ||
syntaxFacts.SyntaxKinds.InterpolatedStringTextToken == token.RawKind)
{
// This allocated. But we only do it in the string case. For all other tokens
// we don't need any allocations.
if (!IsOnSingleLine(token.ToString()))
{
return false;
}
}
// Any other type of token is on a single line.
return true;
}
private static bool IsOnSingleLine(ISyntaxFacts syntaxFacts, SyntaxTriviaList triviaList, bool checkTrivia)
{
if (checkTrivia)
{
foreach (var trivia in triviaList)
{
if (trivia.HasStructure)
{
// For structured trivia, we recurse into the trivia to see if it
// is on a single line or not. If it isn't, then we're definitely
// not on a single line.
if (!IsOnSingleLine(syntaxFacts, trivia.GetStructure()!, fullSpan: true))
{
return false;
}
}
else if (syntaxFacts.IsEndOfLineTrivia(trivia))
{
// Contained an end-of-line trivia. Definitely not on a single line.
return false;
}
else if (!syntaxFacts.IsWhitespaceTrivia(trivia))
{
// Was some other form of trivia (like a comment). Easiest thing
// to do is just stringify this and count the number of newlines.
// these should be rare. So the allocation here is ok.
if (!IsOnSingleLine(trivia.ToString()))
{
return false;
}
}
}
}
return true;
}
private static bool IsOnSingleLine(string value)
=> value.GetNumberOfLineBreaks() == 0;
public static bool ContainsInterleavedDirective(
this ISyntaxFacts syntaxFacts, ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken)
{
if (nodes.Length > 0)
{
var span = TextSpan.FromBounds(nodes.First().Span.Start, nodes.Last().Span.End);
foreach (var node in nodes)
{
cancellationToken.ThrowIfCancellationRequested();
if (ContainsInterleavedDirective(syntaxFacts, span, node, cancellationToken))
return true;
}
}
return false;
}
public static bool ContainsInterleavedDirective(this ISyntaxFacts syntaxFacts, SyntaxNode node, CancellationToken cancellationToken)
=> ContainsInterleavedDirective(syntaxFacts, node.Span, node, cancellationToken);
public static bool ContainsInterleavedDirective(
this ISyntaxFacts syntaxFacts, TextSpan span, SyntaxNode node, CancellationToken cancellationToken)
{
foreach (var token in node.DescendantTokens())
{
if (syntaxFacts.ContainsInterleavedDirective(span, token, cancellationToken))
return true;
}
return false;
}
public static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, IEnumerable<SyntaxNode> nodes)
{
if (nodes == null || nodes.IsEmpty())
{
return false;
}
return SpansPreprocessorDirective(syntaxFacts, nodes.SelectMany(n => n.DescendantTokens()));
}
/// <summary>
/// Determines if there is preprocessor trivia *between* any of the <paramref name="tokens"/>
/// provided. The <paramref name="tokens"/> will be deduped and then ordered by position.
/// Specifically, the first token will not have it's leading trivia checked, and the last
/// token will not have it's trailing trivia checked. All other trivia will be checked to
/// see if it contains a preprocessor directive.
/// </summary>
public static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, IEnumerable<SyntaxToken> tokens)
{
// we want to check all leading trivia of all tokens (except the
// first one), and all trailing trivia of all tokens (except the
// last one).
var first = true;
var previousToken = default(SyntaxToken);
// Allow duplicate nodes/tokens to be passed in. Also, allow the nodes/tokens
// to not be in any particular order when passed in.
var orderedTokens = tokens.Distinct().OrderBy(t => t.SpanStart);
foreach (var token in orderedTokens)
{
if (first)
{
first = false;
}
else
{
// check the leading trivia of this token, and the trailing trivia
// of the previous token.
if (SpansPreprocessorDirective(syntaxFacts, token.LeadingTrivia) ||
SpansPreprocessorDirective(syntaxFacts, previousToken.TrailingTrivia))
{
return true;
}
}
previousToken = token;
}
return false;
}
private static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, SyntaxTriviaList list)
=> list.Any(t => syntaxFacts.IsPreprocessorDirective(t));
public static bool IsLegalIdentifier(this ISyntaxFacts syntaxFacts, string name)
{
if (name.Length == 0)
{
return false;
}
if (!syntaxFacts.IsIdentifierStartCharacter(name[0]))
{
return false;
}
for (var i = 1; i < name.Length; i++)
{
if (!syntaxFacts.IsIdentifierPartCharacter(name[i]))
{
return false;
}
}
return true;
}
public static bool IsReservedOrContextualKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> syntaxFacts.IsReservedKeyword(token) || syntaxFacts.IsContextualKeyword(token);
public static bool IsWord(this ISyntaxFacts syntaxFacts, SyntaxToken token)
{
return syntaxFacts.IsIdentifier(token)
|| syntaxFacts.IsReservedOrContextualKeyword(token)
|| syntaxFacts.IsPreprocessorKeyword(token);
}
public static bool IsRegularOrDocumentationComment(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> syntaxFacts.IsRegularComment(trivia) || syntaxFacts.IsDocumentationComment(trivia);
public static void GetPartsOfAssignmentStatement(
this ISyntaxFacts syntaxFacts, SyntaxNode statement,
out SyntaxNode left, out SyntaxNode right)
{
syntaxFacts.GetPartsOfAssignmentStatement(statement, out left, out _, out right);
}
public static SyntaxNode GetExpressionOfInvocationExpression(
this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfInvocationExpression(node, out var expression, out _);
return expression;
}
public static SyntaxNode Unparenthesize(
this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
SyntaxToken openParenToken;
SyntaxNode operand;
SyntaxToken closeParenToken;
if (syntaxFacts.IsParenthesizedPattern(node))
{
syntaxFacts.GetPartsOfParenthesizedPattern(node,
out openParenToken, out operand, out closeParenToken);
}
else
{
syntaxFacts.GetPartsOfParenthesizedExpression(node,
out openParenToken, out operand, out closeParenToken);
}
var leadingTrivia = openParenToken.LeadingTrivia
.Concat(openParenToken.TrailingTrivia)
.Where(t => !syntaxFacts.IsElastic(t))
.Concat(operand.GetLeadingTrivia());
var trailingTrivia = operand.GetTrailingTrivia()
.Concat(closeParenToken.LeadingTrivia)
.Where(t => !syntaxFacts.IsElastic(t))
.Concat(closeParenToken.TrailingTrivia);
var resultNode = operand
.WithLeadingTrivia(leadingTrivia)
.WithTrailingTrivia(trailingTrivia);
// If there's no trivia between the original node and the tokens around it, then add
// elastic markers so the formatting engine will spaces if necessary to keep things
// parseable.
if (resultNode.GetLeadingTrivia().Count == 0)
{
var previousToken = node.GetFirstToken().GetPreviousToken();
if (previousToken.TrailingTrivia.Count == 0 &&
syntaxFacts.IsWordOrNumber(previousToken) &&
syntaxFacts.IsWordOrNumber(resultNode.GetFirstToken()))
{
resultNode = resultNode.WithPrependedLeadingTrivia(syntaxFacts.ElasticMarker);
}
}
if (resultNode.GetTrailingTrivia().Count == 0)
{
var nextToken = node.GetLastToken().GetNextToken();
if (nextToken.LeadingTrivia.Count == 0 &&
syntaxFacts.IsWordOrNumber(nextToken) &&
syntaxFacts.IsWordOrNumber(resultNode.GetLastToken()))
{
resultNode = resultNode.WithAppendedTrailingTrivia(syntaxFacts.ElasticMarker);
}
}
return resultNode;
}
private static bool IsWordOrNumber(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> syntaxFacts.IsWord(token) || syntaxFacts.IsNumericLiteral(token);
public static bool SpansPreprocessorDirective(this ISyntaxFacts service, SyntaxNode node)
=> service.SpansPreprocessorDirective(SpecializedCollections.SingletonEnumerable(node));
public static bool SpansPreprocessorDirective(this ISyntaxFacts service, params SyntaxNode[] nodes)
=> service.SpansPreprocessorDirective(nodes);
public static bool IsWhitespaceOrEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> syntaxFacts.IsWhitespaceTrivia(trivia) || syntaxFacts.IsEndOfLineTrivia(trivia);
public static void GetPartsOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode left, out SyntaxNode right)
=> syntaxFacts.GetPartsOfBinaryExpression(node, out left, out _, out right);
public static SyntaxNode GetPatternOfParenthesizedPattern(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfParenthesizedPattern(node, out _, out var pattern, out _);
return pattern;
}
public static SyntaxToken GetOperatorTokenOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfBinaryExpression(node, out _, out var token, out _);
return token;
}
public static bool IsAnonymousOrLocalFunction(this ISyntaxFacts syntaxFacts, SyntaxNode node)
=> syntaxFacts.IsAnonymousFunctionExpression(node) ||
syntaxFacts.IsLocalFunctionStatement(node);
public static SyntaxNode? GetExpressionOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfElementAccessExpression(node, out var expression, out _);
return expression;
}
public static SyntaxNode? GetArgumentListOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfElementAccessExpression(node, out _, out var argumentList);
return argumentList;
}
public static SyntaxNode GetExpressionOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfConditionalAccessExpression(node, out var expression, out _);
return expression;
}
public static SyntaxToken GetOperatorTokenOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var operatorToken, out _);
return operatorToken;
}
public static void GetPartsOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode name)
=> syntaxFacts.GetPartsOfMemberAccessExpression(node, out expression, out _, out name);
public static void GetPartsOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode whenNotNull)
=> syntaxFacts.GetPartsOfConditionalAccessExpression(node, out expression, out _, out whenNotNull);
public static TextSpan GetSpanWithoutAttributes(this ISyntaxFacts syntaxFacts, SyntaxNode root, SyntaxNode node)
{
// Span without AttributeLists
// - No AttributeLists -> original .Span
// - Some AttributeLists -> (first non-trivia/comment Token.Span.Begin, original.Span.End)
// - We need to be mindful about comments due to:
// // [Test1]
// //Comment1
// [||]object Property1 { get; set; }
// the comment node being part of the next token's (`object`) leading trivia and not the AttributeList's node.
// - In case only attribute is written we need to be careful to not to use next (unrelated) token as beginning current the node.
var attributeList = syntaxFacts.GetAttributeLists(node);
if (attributeList.Any())
{
var endOfAttributeLists = attributeList.Last().Span.End;
var afterAttributesToken = root.FindTokenOnRightOfPosition(endOfAttributeLists);
var endOfNode = node.Span.End;
var startOfNodeWithoutAttributes = Math.Min(afterAttributesToken.Span.Start, endOfNode);
return TextSpan.FromBounds(startOfNodeWithoutAttributes, endOfNode);
}
return node.Span;
}
/// <summary>
/// Gets the statement container node for the statement <paramref name="node"/>.
/// </summary>
/// <param name="syntaxFacts">The <see cref="ISyntaxFacts"/> implementation.</param>
/// <param name="node">The statement.</param>
/// <returns>The statement container for <paramref name="node"/>.</returns>
public static SyntaxNode? GetStatementContainer(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
for (var current = node; current is object; current = current.Parent)
{
if (syntaxFacts.IsStatementContainer(current.Parent))
{
return current.Parent;
}
}
return null;
}
/// <summary>
/// Similar to <see cref="ISyntaxFacts.GetStandaloneExpression(SyntaxNode)"/>, this gets the containing
/// expression that is actually a language expression and not just typed as an ExpressionSyntax for convenience.
/// However, this goes beyond that that method in that if this expression is the RHS of a conditional access
/// (i.e. <c>a?.b()</c>) it will also return the root of the conditional access expression tree.
/// <para/> The intuition here is that this will give the topmost expression node that could realistically be
/// replaced with any other expression. For example, with <c>a?.b()</c> technically <c>.b()</c> is an
/// expression. But that cannot be replaced with something like <c>(1 + 1)</c> (as <c>a?.(1 + 1)</c> is not
/// legal). However, in <c>a?.b()</c>, then <c>a</c> itself could be replaced with <c>(1 + 1)?.b()</c> to form
/// a legal expression.
/// </summary>
public static SyntaxNode GetRootStandaloneExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
// First, make sure we're on a construct the language things is a standalone expression.
var standalone = syntaxFacts.GetStandaloneExpression(node);
// Then, if this is the RHS of a `?`, walk up to the top of that tree to get the final standalone expression.
return syntaxFacts.GetRootConditionalAccessExpression(standalone) ?? standalone;
}
#region GetXXXOfYYY Members
public static SyntaxNode? GetArgumentListOfInvocationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfInvocationExpression(node, out _, out var argumentList);
return argumentList;
}
public static SyntaxNode? GetArgumentListOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfObjectCreationExpression(node, out _, out var argumentList, out _);
return argumentList;
}
public static SyntaxNode GetExpressionOfParenthesizedExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfParenthesizedExpression(node, out _, out var expression, out _);
return expression;
}
public static SyntaxList<SyntaxNode> GetImportsOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out _, out var imports, out _);
return imports;
}
public static SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfCompilationUnit(node, out var imports, out _, out _);
return imports;
}
public static SyntaxNode? GetInitializerOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfObjectCreationExpression(node, out _, out _, out var initializer);
return initializer;
}
public static SyntaxList<SyntaxNode> GetMembersOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out _, out _, out var members);
return members;
}
public static SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfCompilationUnit(node, out _, out _, out var members);
return members;
}
public static SyntaxNode GetNameOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out var name, out _, out _);
return name;
}
public static SyntaxNode GetNameOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var name);
return name;
}
public static SyntaxNode GetOperandOfPrefixUnaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfPrefixUnaryExpression(node, out _, out var operand);
return operand;
}
public static SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfPrefixUnaryExpression(node, out var operatorToken, out _);
return operatorToken;
}
public static SyntaxNode GetTypeOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfObjectCreationExpression(node, out var type, out _, out _);
return type;
}
#endregion
#region IsXXXOfYYY members
public static bool IsExpressionOfAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsAwaitExpression(parent))
return false;
return node == syntaxFacts.GetExpressionOfAwaitExpression(parent);
}
public static bool IsExpressionOfInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsInvocationExpression(parent))
return false;
syntaxFacts.GetPartsOfInvocationExpression(parent, out var expression, out _);
return node == expression;
}
public static bool IsExpressionOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsMemberAccessExpression(parent))
return false;
syntaxFacts.GetPartsOfMemberAccessExpression(parent, out var expression, out _);
return node == expression;
}
public static bool IsRightOfQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsQualifiedName(parent))
return false;
syntaxFacts.GetPartsOfQualifiedName(parent, out _, out _, out var right);
return node == right;
}
public static bool IsTypeOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsObjectCreationExpression(parent))
return false;
syntaxFacts.GetPartsOfObjectCreationExpression(parent, out var type, out _, out _);
return type == node;
}
#endregion
#region ISyntaxKinds forwarding methods
#region trivia
public static bool IsEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia;
public static bool IsWhitespaceTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.WhitespaceTrivia;
public static bool IsSkippedTokensTrivia(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.SkippedTokensTrivia;
#endregion
#region keywords
public static bool IsAwaitKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.AwaitKeyword;
public static bool IsGlobalNamespaceKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.GlobalKeyword;
#endregion
#region literal tokens
public static bool IsCharacterLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralToken;
public static bool IsStringLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.StringLiteralToken;
#endregion
#region tokens
public static bool IsIdentifier(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.IdentifierToken;
public static bool IsHashToken(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.HashToken;
public static bool IsInterpolatedStringTextToken(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringTextToken;
#endregion
#region names
public static bool IsGenericName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.GenericName;
public static bool IsIdentifierName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.IdentifierName;
public static bool IsQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.QualifiedName;
#endregion
#region types
public static bool IsTupleType(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TupleType;
#endregion
#region literal expressions
public static bool IsCharacterLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralExpression;
public static bool IsDefaultLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.DefaultLiteralExpression;
public static bool IsFalseLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.FalseLiteralExpression;
public static bool IsNumericLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.NumericLiteralExpression;
public static bool IsNullLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.NullLiteralExpression;
public static bool IsStringLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.StringLiteralExpression;
public static bool IsTrueLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TrueLiteralExpression;
#endregion
#region expressions
public static bool IsAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.AwaitExpression;
public static bool IsBaseExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.BaseExpression;
public static bool IsConditionalAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ConditionalAccessExpression;
public static bool IsImplicitObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node != null && node.RawKind == syntaxFacts.SyntaxKinds.ImplicitObjectCreationExpression;
public static bool IsInterpolatedStringExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringExpression;
public static bool IsInterpolation(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.Interpolation;
public static bool IsInterpolatedStringText(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringText;
public static bool IsInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.InvocationExpression;
public static bool IsLogicalAndExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LogicalAndExpression;
public static bool IsLogicalOrExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LogicalOrExpression;
public static bool IsLogicalNotExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LogicalNotExpression;
public static bool IsObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ObjectCreationExpression;
public static bool IsParenthesizedExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ParenthesizedExpression;
public static bool IsQueryExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.QueryExpression;
public static bool IsSimpleMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.SimpleMemberAccessExpression;
public static bool IsThisExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ThisExpression;
public static bool IsThrowExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node != null && node.RawKind == syntaxFacts.SyntaxKinds.ThrowExpression;
public static bool IsTupleExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TupleExpression;
public static bool ContainsGlobalStatement(this ISyntaxFacts syntaxFacts, SyntaxNode node)
=> node.ChildNodes().Any(c => c.RawKind == syntaxFacts.SyntaxKinds.GlobalStatement);
#endregion
#region statements
public static bool IsExpressionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ExpressionStatement;
public static bool IsForEachStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ForEachStatement;
public static bool IsLocalDeclarationStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LocalDeclarationStatement;
public static bool IsLocalFunctionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node != null && node.RawKind == syntaxFacts.SyntaxKinds.LocalFunctionStatement;
public static bool IsLockStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LockStatement;
public static bool IsReturnStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ReturnStatement;
public static bool IsThrowStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ThrowStatement;
public static bool IsUsingStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.UsingStatement;
#endregion
#region members/declarations
public static bool IsAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.Attribute;
public static bool IsClassDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ClassDeclaration;
public static bool IsGlobalAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> syntaxFacts.IsGlobalAssemblyAttribute(node) || syntaxFacts.IsGlobalModuleAttribute(node);
public static bool IsParameter(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.Parameter;
public static bool IsTypeConstraint(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TypeConstraint;
public static bool IsVariableDeclarator(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.VariableDeclarator;
public static bool IsFieldDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.FieldDeclaration;
public static bool IsTypeArgumentList(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TypeArgumentList;
#endregion
#region clauses
public static bool IsEqualsValueClause(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.EqualsValueClause;
#endregion
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal static class ISyntaxFactsExtensions
{
private static readonly ObjectPool<Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)>> s_stackPool
= SharedPools.Default<Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)>>();
public static bool IsOnSingleLine(this ISyntaxFacts syntaxFacts, SyntaxNode node, bool fullSpan)
{
// The stack logic assumes the initial node is not null
Contract.ThrowIfNull(node);
// Use an actual Stack so we can write out deeply recursive structures without overflowing.
// Note: algorithm is taken from GreenNode.WriteTo.
//
// General approach is that we recurse down the nodes, using a real stack object to
// keep track of what node we're on. If full-span is true we'll examine all tokens
// and all the trivia on each token. If full-span is false we'll examine all tokens
// but we'll ignore the leading trivia on the very first trivia and the trailing trivia
// on the very last token.
var stack = s_stackPool.Allocate();
stack.Push((node, leading: fullSpan, trailing: fullSpan));
var result = IsOnSingleLine(syntaxFacts, stack);
s_stackPool.ClearAndFree(stack);
return result;
}
private static bool IsOnSingleLine(
ISyntaxFacts syntaxFacts, Stack<(SyntaxNodeOrToken nodeOrToken, bool leading, bool trailing)> stack)
{
while (stack.Count > 0)
{
var (currentNodeOrToken, currentLeading, currentTrailing) = stack.Pop();
if (currentNodeOrToken.IsToken)
{
// If this token isn't on a single line, then the original node definitely
// isn't on a single line.
if (!IsOnSingleLine(syntaxFacts, currentNodeOrToken.AsToken(), currentLeading, currentTrailing))
return false;
}
else
{
var currentNode = currentNodeOrToken.AsNode()!;
var childNodesAndTokens = currentNode.ChildNodesAndTokens();
var childCount = childNodesAndTokens.Count;
// Walk the children of this node in reverse, putting on the stack to process.
// This way we process the children in the actual child-order they are in for
// this node.
var index = 0;
foreach (var child in childNodesAndTokens.Reverse())
{
// Since we're walking the children in reverse, if we're on hte 0th item,
// that's the last child.
var last = index == 0;
// Once we get all the way to the end of the reversed list, we're actually
// on the first.
var first = index == childCount - 1;
// We want the leading trivia if we've asked for it, or if we're not the first
// token being processed. We want the trailing trivia if we've asked for it,
// or if we're not the last token being processed.
stack.Push((child, currentLeading | !first, currentTrailing | !last));
index++;
}
}
}
// All tokens were on a single line. This node is on a single line.
return true;
}
private static bool IsOnSingleLine(ISyntaxFacts syntaxFacts, SyntaxToken token, bool leading, bool trailing)
{
// If any of our trivia is not on a single line, then we're not on a single line.
if (!IsOnSingleLine(syntaxFacts, token.LeadingTrivia, leading) ||
!IsOnSingleLine(syntaxFacts, token.TrailingTrivia, trailing))
{
return false;
}
// Only string literals can span multiple lines. Only need to check those.
if (syntaxFacts.SyntaxKinds.StringLiteralToken == token.RawKind ||
syntaxFacts.SyntaxKinds.InterpolatedStringTextToken == token.RawKind)
{
// This allocated. But we only do it in the string case. For all other tokens
// we don't need any allocations.
if (!IsOnSingleLine(token.ToString()))
{
return false;
}
}
// Any other type of token is on a single line.
return true;
}
private static bool IsOnSingleLine(ISyntaxFacts syntaxFacts, SyntaxTriviaList triviaList, bool checkTrivia)
{
if (checkTrivia)
{
foreach (var trivia in triviaList)
{
if (trivia.HasStructure)
{
// For structured trivia, we recurse into the trivia to see if it
// is on a single line or not. If it isn't, then we're definitely
// not on a single line.
if (!IsOnSingleLine(syntaxFacts, trivia.GetStructure()!, fullSpan: true))
{
return false;
}
}
else if (syntaxFacts.IsEndOfLineTrivia(trivia))
{
// Contained an end-of-line trivia. Definitely not on a single line.
return false;
}
else if (!syntaxFacts.IsWhitespaceTrivia(trivia))
{
// Was some other form of trivia (like a comment). Easiest thing
// to do is just stringify this and count the number of newlines.
// these should be rare. So the allocation here is ok.
if (!IsOnSingleLine(trivia.ToString()))
{
return false;
}
}
}
}
return true;
}
private static bool IsOnSingleLine(string value)
=> value.GetNumberOfLineBreaks() == 0;
public static bool ContainsInterleavedDirective(
this ISyntaxFacts syntaxFacts, ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken)
{
if (nodes.Length > 0)
{
var span = TextSpan.FromBounds(nodes.First().Span.Start, nodes.Last().Span.End);
foreach (var node in nodes)
{
cancellationToken.ThrowIfCancellationRequested();
if (ContainsInterleavedDirective(syntaxFacts, span, node, cancellationToken))
return true;
}
}
return false;
}
public static bool ContainsInterleavedDirective(this ISyntaxFacts syntaxFacts, SyntaxNode node, CancellationToken cancellationToken)
=> ContainsInterleavedDirective(syntaxFacts, node.Span, node, cancellationToken);
public static bool ContainsInterleavedDirective(
this ISyntaxFacts syntaxFacts, TextSpan span, SyntaxNode node, CancellationToken cancellationToken)
{
foreach (var token in node.DescendantTokens())
{
if (syntaxFacts.ContainsInterleavedDirective(span, token, cancellationToken))
return true;
}
return false;
}
public static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, IEnumerable<SyntaxNode> nodes)
{
if (nodes == null || nodes.IsEmpty())
{
return false;
}
return SpansPreprocessorDirective(syntaxFacts, nodes.SelectMany(n => n.DescendantTokens()));
}
/// <summary>
/// Determines if there is preprocessor trivia *between* any of the <paramref name="tokens"/>
/// provided. The <paramref name="tokens"/> will be deduped and then ordered by position.
/// Specifically, the first token will not have it's leading trivia checked, and the last
/// token will not have it's trailing trivia checked. All other trivia will be checked to
/// see if it contains a preprocessor directive.
/// </summary>
public static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, IEnumerable<SyntaxToken> tokens)
{
// we want to check all leading trivia of all tokens (except the
// first one), and all trailing trivia of all tokens (except the
// last one).
var first = true;
var previousToken = default(SyntaxToken);
// Allow duplicate nodes/tokens to be passed in. Also, allow the nodes/tokens
// to not be in any particular order when passed in.
var orderedTokens = tokens.Distinct().OrderBy(t => t.SpanStart);
foreach (var token in orderedTokens)
{
if (first)
{
first = false;
}
else
{
// check the leading trivia of this token, and the trailing trivia
// of the previous token.
if (SpansPreprocessorDirective(syntaxFacts, token.LeadingTrivia) ||
SpansPreprocessorDirective(syntaxFacts, previousToken.TrailingTrivia))
{
return true;
}
}
previousToken = token;
}
return false;
}
private static bool SpansPreprocessorDirective(this ISyntaxFacts syntaxFacts, SyntaxTriviaList list)
=> list.Any(t => syntaxFacts.IsPreprocessorDirective(t));
public static bool IsLegalIdentifier(this ISyntaxFacts syntaxFacts, string name)
{
if (name.Length == 0)
{
return false;
}
if (!syntaxFacts.IsIdentifierStartCharacter(name[0]))
{
return false;
}
for (var i = 1; i < name.Length; i++)
{
if (!syntaxFacts.IsIdentifierPartCharacter(name[i]))
{
return false;
}
}
return true;
}
public static bool IsReservedOrContextualKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> syntaxFacts.IsReservedKeyword(token) || syntaxFacts.IsContextualKeyword(token);
public static bool IsWord(this ISyntaxFacts syntaxFacts, SyntaxToken token)
{
return syntaxFacts.IsIdentifier(token)
|| syntaxFacts.IsReservedOrContextualKeyword(token)
|| syntaxFacts.IsPreprocessorKeyword(token);
}
public static bool IsRegularOrDocumentationComment(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> syntaxFacts.IsRegularComment(trivia) || syntaxFacts.IsDocumentationComment(trivia);
public static void GetPartsOfAssignmentStatement(
this ISyntaxFacts syntaxFacts, SyntaxNode statement,
out SyntaxNode left, out SyntaxNode right)
{
syntaxFacts.GetPartsOfAssignmentStatement(statement, out left, out _, out right);
}
public static SyntaxNode GetExpressionOfInvocationExpression(
this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfInvocationExpression(node, out var expression, out _);
return expression;
}
public static SyntaxNode Unparenthesize(
this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
SyntaxToken openParenToken;
SyntaxNode operand;
SyntaxToken closeParenToken;
if (syntaxFacts.IsParenthesizedPattern(node))
{
syntaxFacts.GetPartsOfParenthesizedPattern(node,
out openParenToken, out operand, out closeParenToken);
}
else
{
syntaxFacts.GetPartsOfParenthesizedExpression(node,
out openParenToken, out operand, out closeParenToken);
}
var leadingTrivia = openParenToken.LeadingTrivia
.Concat(openParenToken.TrailingTrivia)
.Where(t => !syntaxFacts.IsElastic(t))
.Concat(operand.GetLeadingTrivia());
var trailingTrivia = operand.GetTrailingTrivia()
.Concat(closeParenToken.LeadingTrivia)
.Where(t => !syntaxFacts.IsElastic(t))
.Concat(closeParenToken.TrailingTrivia);
var resultNode = operand
.WithLeadingTrivia(leadingTrivia)
.WithTrailingTrivia(trailingTrivia);
// If there's no trivia between the original node and the tokens around it, then add
// elastic markers so the formatting engine will spaces if necessary to keep things
// parseable.
if (resultNode.GetLeadingTrivia().Count == 0)
{
var previousToken = node.GetFirstToken().GetPreviousToken();
if (previousToken.TrailingTrivia.Count == 0 &&
syntaxFacts.IsWordOrNumber(previousToken) &&
syntaxFacts.IsWordOrNumber(resultNode.GetFirstToken()))
{
resultNode = resultNode.WithPrependedLeadingTrivia(syntaxFacts.ElasticMarker);
}
}
if (resultNode.GetTrailingTrivia().Count == 0)
{
var nextToken = node.GetLastToken().GetNextToken();
if (nextToken.LeadingTrivia.Count == 0 &&
syntaxFacts.IsWordOrNumber(nextToken) &&
syntaxFacts.IsWordOrNumber(resultNode.GetLastToken()))
{
resultNode = resultNode.WithAppendedTrailingTrivia(syntaxFacts.ElasticMarker);
}
}
return resultNode;
}
private static bool IsWordOrNumber(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> syntaxFacts.IsWord(token) || syntaxFacts.IsNumericLiteral(token);
public static bool SpansPreprocessorDirective(this ISyntaxFacts service, SyntaxNode node)
=> service.SpansPreprocessorDirective(SpecializedCollections.SingletonEnumerable(node));
public static bool SpansPreprocessorDirective(this ISyntaxFacts service, params SyntaxNode[] nodes)
=> service.SpansPreprocessorDirective(nodes);
public static bool IsWhitespaceOrEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> syntaxFacts.IsWhitespaceTrivia(trivia) || syntaxFacts.IsEndOfLineTrivia(trivia);
public static void GetPartsOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode left, out SyntaxNode right)
=> syntaxFacts.GetPartsOfBinaryExpression(node, out left, out _, out right);
public static SyntaxNode GetPatternOfParenthesizedPattern(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfParenthesizedPattern(node, out _, out var pattern, out _);
return pattern;
}
public static SyntaxToken GetOperatorTokenOfBinaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfBinaryExpression(node, out _, out var token, out _);
return token;
}
public static bool IsAnonymousOrLocalFunction(this ISyntaxFacts syntaxFacts, SyntaxNode node)
=> syntaxFacts.IsAnonymousFunctionExpression(node) ||
syntaxFacts.IsLocalFunctionStatement(node);
public static SyntaxNode? GetExpressionOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfElementAccessExpression(node, out var expression, out _);
return expression;
}
public static SyntaxNode? GetArgumentListOfElementAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfElementAccessExpression(node, out _, out var argumentList);
return argumentList;
}
public static SyntaxNode GetExpressionOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfConditionalAccessExpression(node, out var expression, out _);
return expression;
}
public static SyntaxToken GetOperatorTokenOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var operatorToken, out _);
return operatorToken;
}
public static void GetPartsOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode name)
=> syntaxFacts.GetPartsOfMemberAccessExpression(node, out expression, out _, out name);
public static void GetPartsOfConditionalAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node, out SyntaxNode expression, out SyntaxNode whenNotNull)
=> syntaxFacts.GetPartsOfConditionalAccessExpression(node, out expression, out _, out whenNotNull);
public static TextSpan GetSpanWithoutAttributes(this ISyntaxFacts syntaxFacts, SyntaxNode root, SyntaxNode node)
{
// Span without AttributeLists
// - No AttributeLists -> original .Span
// - Some AttributeLists -> (first non-trivia/comment Token.Span.Begin, original.Span.End)
// - We need to be mindful about comments due to:
// // [Test1]
// //Comment1
// [||]object Property1 { get; set; }
// the comment node being part of the next token's (`object`) leading trivia and not the AttributeList's node.
// - In case only attribute is written we need to be careful to not to use next (unrelated) token as beginning current the node.
var attributeList = syntaxFacts.GetAttributeLists(node);
if (attributeList.Any())
{
var endOfAttributeLists = attributeList.Last().Span.End;
var afterAttributesToken = root.FindTokenOnRightOfPosition(endOfAttributeLists);
var endOfNode = node.Span.End;
var startOfNodeWithoutAttributes = Math.Min(afterAttributesToken.Span.Start, endOfNode);
return TextSpan.FromBounds(startOfNodeWithoutAttributes, endOfNode);
}
return node.Span;
}
/// <summary>
/// Gets the statement container node for the statement <paramref name="node"/>.
/// </summary>
/// <param name="syntaxFacts">The <see cref="ISyntaxFacts"/> implementation.</param>
/// <param name="node">The statement.</param>
/// <returns>The statement container for <paramref name="node"/>.</returns>
public static SyntaxNode? GetStatementContainer(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
for (var current = node; current is object; current = current.Parent)
{
if (syntaxFacts.IsStatementContainer(current.Parent))
{
return current.Parent;
}
}
return null;
}
/// <summary>
/// Similar to <see cref="ISyntaxFacts.GetStandaloneExpression(SyntaxNode)"/>, this gets the containing
/// expression that is actually a language expression and not just typed as an ExpressionSyntax for convenience.
/// However, this goes beyond that that method in that if this expression is the RHS of a conditional access
/// (i.e. <c>a?.b()</c>) it will also return the root of the conditional access expression tree.
/// <para/> The intuition here is that this will give the topmost expression node that could realistically be
/// replaced with any other expression. For example, with <c>a?.b()</c> technically <c>.b()</c> is an
/// expression. But that cannot be replaced with something like <c>(1 + 1)</c> (as <c>a?.(1 + 1)</c> is not
/// legal). However, in <c>a?.b()</c>, then <c>a</c> itself could be replaced with <c>(1 + 1)?.b()</c> to form
/// a legal expression.
/// </summary>
public static SyntaxNode GetRootStandaloneExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
// First, make sure we're on a construct the language things is a standalone expression.
var standalone = syntaxFacts.GetStandaloneExpression(node);
// Then, if this is the RHS of a `?`, walk up to the top of that tree to get the final standalone expression.
return syntaxFacts.GetRootConditionalAccessExpression(standalone) ?? standalone;
}
#region GetXXXOfYYY Members
public static SyntaxNode? GetArgumentListOfInvocationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfInvocationExpression(node, out _, out var argumentList);
return argumentList;
}
public static SyntaxNode? GetArgumentListOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfObjectCreationExpression(node, out _, out var argumentList, out _);
return argumentList;
}
public static SyntaxNode GetExpressionOfParenthesizedExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfParenthesizedExpression(node, out _, out var expression, out _);
return expression;
}
public static SyntaxList<SyntaxNode> GetImportsOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out _, out var imports, out _);
return imports;
}
public static SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfCompilationUnit(node, out var imports, out _, out _);
return imports;
}
public static SyntaxNode? GetInitializerOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfObjectCreationExpression(node, out _, out _, out var initializer);
return initializer;
}
public static SyntaxList<SyntaxNode> GetMembersOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out _, out _, out var members);
return members;
}
public static SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfCompilationUnit(node, out _, out _, out var members);
return members;
}
public static SyntaxNode GetNameOfBaseNamespaceDeclaration(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfBaseNamespaceDeclaration(node, out var name, out _, out _);
return name;
}
public static SyntaxNode GetNameOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfMemberAccessExpression(node, out _, out var name);
return name;
}
public static SyntaxNode GetOperandOfPrefixUnaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfPrefixUnaryExpression(node, out _, out var operand);
return operand;
}
public static SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfPrefixUnaryExpression(node, out var operatorToken, out _);
return operatorToken;
}
public static SyntaxNode GetTypeOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, SyntaxNode node)
{
syntaxFacts.GetPartsOfObjectCreationExpression(node, out var type, out _, out _);
return type;
}
#endregion
#region IsXXXOfYYY members
public static bool IsExpressionOfAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsAwaitExpression(parent))
return false;
return node == syntaxFacts.GetExpressionOfAwaitExpression(parent);
}
public static bool IsExpressionOfInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsInvocationExpression(parent))
return false;
syntaxFacts.GetPartsOfInvocationExpression(parent, out var expression, out _);
return node == expression;
}
public static bool IsExpressionOfMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsMemberAccessExpression(parent))
return false;
syntaxFacts.GetPartsOfMemberAccessExpression(parent, out var expression, out _);
return node == expression;
}
public static bool IsRightOfQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsQualifiedName(parent))
return false;
syntaxFacts.GetPartsOfQualifiedName(parent, out _, out _, out var right);
return node == right;
}
public static bool IsTypeOfObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
{
var parent = node?.Parent;
if (!syntaxFacts.IsObjectCreationExpression(parent))
return false;
syntaxFacts.GetPartsOfObjectCreationExpression(parent, out var type, out _, out _);
return type == node;
}
#endregion
#region ISyntaxKinds forwarding methods
#region trivia
public static bool IsEndOfLineTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia;
public static bool IsMultiLineCommentTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.MultiLineCommentTrivia;
public static bool IsMultiLineDocCommentTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.MultiLineDocCommentTrivia;
public static bool IsShebangDirectiveTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.ShebangDirectiveTrivia;
public static bool IsSingleLineCommentTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.SingleLineCommentTrivia;
public static bool IsSingleLineDocCommentTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.SingleLineDocCommentTrivia;
public static bool IsWhitespaceTrivia(this ISyntaxFacts syntaxFacts, SyntaxTrivia trivia)
=> trivia.RawKind == syntaxFacts.SyntaxKinds.WhitespaceTrivia;
public static bool IsSkippedTokensTrivia(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.SkippedTokensTrivia;
#endregion
#region keywords
public static bool IsAwaitKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.AwaitKeyword;
public static bool IsGlobalNamespaceKeyword(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.GlobalKeyword;
#endregion
#region literal tokens
public static bool IsCharacterLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralToken;
public static bool IsStringLiteral(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.StringLiteralToken;
#endregion
#region tokens
public static bool IsIdentifier(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.IdentifierToken;
public static bool IsHashToken(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.HashToken;
public static bool IsInterpolatedStringTextToken(this ISyntaxFacts syntaxFacts, SyntaxToken token)
=> token.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringTextToken;
#endregion
#region names
public static bool IsGenericName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.GenericName;
public static bool IsIdentifierName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.IdentifierName;
public static bool IsQualifiedName(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.QualifiedName;
#endregion
#region types
public static bool IsTupleType(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TupleType;
#endregion
#region literal expressions
public static bool IsCharacterLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.CharacterLiteralExpression;
public static bool IsDefaultLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.DefaultLiteralExpression;
public static bool IsFalseLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.FalseLiteralExpression;
public static bool IsNumericLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.NumericLiteralExpression;
public static bool IsNullLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.NullLiteralExpression;
public static bool IsStringLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.StringLiteralExpression;
public static bool IsTrueLiteralExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TrueLiteralExpression;
#endregion
#region expressions
public static bool IsAwaitExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.AwaitExpression;
public static bool IsBaseExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.BaseExpression;
public static bool IsConditionalAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ConditionalAccessExpression;
public static bool IsImplicitObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node != null && node.RawKind == syntaxFacts.SyntaxKinds.ImplicitObjectCreationExpression;
public static bool IsInterpolatedStringExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringExpression;
public static bool IsInterpolation(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.Interpolation;
public static bool IsInterpolatedStringText(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.InterpolatedStringText;
public static bool IsInvocationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.InvocationExpression;
public static bool IsLogicalAndExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LogicalAndExpression;
public static bool IsLogicalOrExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LogicalOrExpression;
public static bool IsLogicalNotExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LogicalNotExpression;
public static bool IsObjectCreationExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ObjectCreationExpression;
public static bool IsParenthesizedExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ParenthesizedExpression;
public static bool IsQueryExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.QueryExpression;
public static bool IsSimpleMemberAccessExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.SimpleMemberAccessExpression;
public static bool IsThisExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ThisExpression;
public static bool IsThrowExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node != null && node.RawKind == syntaxFacts.SyntaxKinds.ThrowExpression;
public static bool IsTupleExpression(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TupleExpression;
public static bool ContainsGlobalStatement(this ISyntaxFacts syntaxFacts, SyntaxNode node)
=> node.ChildNodes().Any(c => c.RawKind == syntaxFacts.SyntaxKinds.GlobalStatement);
#endregion
#region statements
public static bool IsExpressionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ExpressionStatement;
public static bool IsForEachStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ForEachStatement;
public static bool IsLocalDeclarationStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LocalDeclarationStatement;
public static bool IsLocalFunctionStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node != null && node.RawKind == syntaxFacts.SyntaxKinds.LocalFunctionStatement;
public static bool IsLockStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.LockStatement;
public static bool IsReturnStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ReturnStatement;
public static bool IsThrowStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ThrowStatement;
public static bool IsUsingStatement(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.UsingStatement;
#endregion
#region members/declarations
public static bool IsAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.Attribute;
public static bool IsClassDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.ClassDeclaration;
public static bool IsGlobalAttribute(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> syntaxFacts.IsGlobalAssemblyAttribute(node) || syntaxFacts.IsGlobalModuleAttribute(node);
public static bool IsParameter(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.Parameter;
public static bool IsTypeConstraint(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TypeConstraint;
public static bool IsVariableDeclarator(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.VariableDeclarator;
public static bool IsFieldDeclaration(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.FieldDeclaration;
public static bool IsTypeArgumentList(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.TypeArgumentList;
#endregion
#region clauses
public static bool IsEqualsValueClause(this ISyntaxFacts syntaxFacts, [NotNullWhen(true)] SyntaxNode? node)
=> node?.RawKind == syntaxFacts.SyntaxKinds.EqualsValueClause;
#endregion
#endregion
}
}
| 1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports System.Diagnostics.CodeAnalysis
#If CODE_STYLE Then
Imports Microsoft.CodeAnalysis.Internal.Editing
#Else
Imports Microsoft.CodeAnalysis.Editing
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Friend Class VisualBasicSyntaxFacts
Inherits AbstractSyntaxFacts
Implements ISyntaxFacts
Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts
Protected Sub New()
End Sub
Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive
Get
Return False
End Get
End Property
Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer
Get
Return CaseInsensitiveComparison.Comparer
End Get
End Property
Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker
Get
Return SyntaxFactory.ElasticMarker
End Get
End Property
Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed
Get
Return SyntaxFactory.ElasticCarriageReturnLineFeed
End Get
End Property
Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds
Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer
Return False
End Function
Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression
Return False
End Function
Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration
Return False
End Function
Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord
Return False
End Function
Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct
Return False
End Function
Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken
Return SyntaxFactory.ParseToken(text, startStatement:=True)
End Function
Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia
Return SyntaxFactory.ParseLeadingTrivia(text)
End Function
Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier
Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier)
Dim needsEscaping = keywordKind <> SyntaxKind.None
Return If(needsEscaping, "[" & identifier & "]", identifier)
End Function
Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return False
End Function
Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator
Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse
(IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax))
End Function
Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword
Return token.IsContextualKeyword()
End Function
Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword
Return token.IsReservedKeyword()
End Function
Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword
Return token.IsPreprocessorKeyword()
End Function
Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext
Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)
End Function
Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace
If token.Kind = SyntaxKind.CloseBraceToken Then
Dim tuples = token.Parent.GetBraces()
openBrace = tuples.openBrace
Return openBrace.Kind = SyntaxKind.OpenBraceToken
End If
Return False
End Function
Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken)
End Function
Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective
Return TypeOf node Is DirectiveTriviaSyntax
End Function
Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo
Select Case node.Kind
Case SyntaxKind.ExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False)
Return True
Case SyntaxKind.EndExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(Nothing, True)
Return True
End Select
Return False
End Function
Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression
' VB doesn't support declaration expressions
Return False
End Function
Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName
Return node.IsParentKind(SyntaxKind.Attribute) AndAlso
DirectCast(node.Parent, AttributeSyntax).Name Is node
End Function
Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression
Dim vbNode = TryCast(node, ExpressionSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName()
End Function
Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression
Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax)
Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node
End Function
Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression
Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax))
End Function
Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression
Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression()
End Function
Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument
Dim arg = TryCast(node, SimpleArgumentSyntax)
Return arg?.NameColonEquals IsNot Nothing
End Function
Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument
Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node)
End Function
Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter
Return DirectCast(node, ParameterSyntax).Identifier?.Identifier
End Function
Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter
Return DirectCast(node, ParameterSyntax).Default
End Function
Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList
Return node.GetParameterList()
End Function
Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList
Return node.IsKind(SyntaxKind.ParameterList)
End Function
Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember
Return HasIncompleteParentMember(node)
End Function
Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName
Return DirectCast(genericName, GenericNameSyntax).Identifier
End Function
Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName
Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso
DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node
End Function
Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment
Return False
End Function
Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement
Return False
End Function
Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement
Return TypeOf node Is StatementSyntax
End Function
Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement
Return TypeOf node Is ExecutableStatementSyntax
End Function
Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody
Return TypeOf node Is MethodBlockBaseSyntax
End Function
Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement
Return DirectCast(node, ReturnStatementSyntax).Expression
End Function
Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsThisConstructorInitializer()
End If
Return False
End Function
Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsBaseConstructorInitializer()
End If
Return False
End Function
Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword
Select Case token.Kind()
Case _
SyntaxKind.JoinKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.AggregateKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.SelectKeyword
Return TypeOf token.Parent Is QueryClauseSyntax
Case SyntaxKind.GroupKeyword
Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation))
Case SyntaxKind.EqualsKeyword
Return TypeOf token.Parent Is JoinConditionSyntax
Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword
Return TypeOf token.Parent Is OrderingSyntax
Case SyntaxKind.InKeyword
Return TypeOf token.Parent Is CollectionRangeVariableSyntax
Case Else
Return False
End Select
End Function
Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None
End Function
Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType = type
End Function
Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType
type = GetPredefinedType(token)
Return type <> PredefinedType.None
End Function
Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType
Select Case token.Kind
Case SyntaxKind.BooleanKeyword
Return PredefinedType.Boolean
Case SyntaxKind.ByteKeyword
Return PredefinedType.Byte
Case SyntaxKind.SByteKeyword
Return PredefinedType.SByte
Case SyntaxKind.IntegerKeyword
Return PredefinedType.Int32
Case SyntaxKind.UIntegerKeyword
Return PredefinedType.UInt32
Case SyntaxKind.ShortKeyword
Return PredefinedType.Int16
Case SyntaxKind.UShortKeyword
Return PredefinedType.UInt16
Case SyntaxKind.LongKeyword
Return PredefinedType.Int64
Case SyntaxKind.ULongKeyword
Return PredefinedType.UInt64
Case SyntaxKind.SingleKeyword
Return PredefinedType.Single
Case SyntaxKind.DoubleKeyword
Return PredefinedType.Double
Case SyntaxKind.DecimalKeyword
Return PredefinedType.Decimal
Case SyntaxKind.StringKeyword
Return PredefinedType.String
Case SyntaxKind.CharKeyword
Return PredefinedType.Char
Case SyntaxKind.ObjectKeyword
Return PredefinedType.Object
Case SyntaxKind.DateKeyword
Return PredefinedType.DateTime
Case Else
Return PredefinedType.None
End Select
End Function
Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None
End Function
Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op
End Function
Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator
op = GetPredefinedOperator(token)
Return op <> PredefinedOperator.None
End Function
Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator
Select Case token.Kind
Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken
Return PredefinedOperator.Addition
Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken
Return PredefinedOperator.Subtraction
Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword
Return PredefinedOperator.BitwiseAnd
Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword
Return PredefinedOperator.BitwiseOr
Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken
Return PredefinedOperator.Concatenate
Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken
Return PredefinedOperator.Division
Case SyntaxKind.EqualsToken
Return PredefinedOperator.Equality
Case SyntaxKind.XorKeyword
Return PredefinedOperator.ExclusiveOr
Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken
Return PredefinedOperator.Exponent
Case SyntaxKind.GreaterThanToken
Return PredefinedOperator.GreaterThan
Case SyntaxKind.GreaterThanEqualsToken
Return PredefinedOperator.GreaterThanOrEqual
Case SyntaxKind.LessThanGreaterThanToken
Return PredefinedOperator.Inequality
Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken
Return PredefinedOperator.IntegerDivision
Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken
Return PredefinedOperator.LeftShift
Case SyntaxKind.LessThanToken
Return PredefinedOperator.LessThan
Case SyntaxKind.LessThanEqualsToken
Return PredefinedOperator.LessThanOrEqual
Case SyntaxKind.LikeKeyword
Return PredefinedOperator.Like
Case SyntaxKind.NotKeyword
Return PredefinedOperator.Complement
Case SyntaxKind.ModKeyword
Return PredefinedOperator.Modulus
Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken
Return PredefinedOperator.Multiplication
Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken
Return PredefinedOperator.RightShift
Case Else
Return PredefinedOperator.None
End Select
End Function
Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText
Return SyntaxFacts.GetText(CType(kind, SyntaxKind))
End Function
Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter
Return SyntaxFacts.IsIdentifierPartCharacter(c)
End Function
Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter
Return SyntaxFacts.IsIdentifierStartCharacter(c)
End Function
Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter
Return c = "["c OrElse c = "]"c
End Function
Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier
Dim token = SyntaxFactory.ParseToken(identifier)
' TODO: There is no way to get the diagnostics to see if any are actually errors?
Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length
End Function
Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]"
End Function
Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter
Return c = "%"c OrElse
c = "&"c OrElse
c = "@"c OrElse
c = "!"c OrElse
c = "#"c OrElse
c = "$"c
End Function
Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence
Return False ' VB does not support identifiers with escaped unicode characters
End Function
Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral
Select Case token.Kind()
Case _
SyntaxKind.IntegerLiteralToken,
SyntaxKind.CharacterLiteralToken,
SyntaxKind.DecimalLiteralToken,
SyntaxKind.FloatingLiteralToken,
SyntaxKind.DateLiteralToken,
SyntaxKind.StringLiteralToken,
SyntaxKind.DollarSignDoubleQuoteToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.InterpolatedStringTextToken,
SyntaxKind.TrueKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.NothingKeyword
Return True
End Select
Return False
End Function
Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral
Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken)
End Function
Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken
Return Me.IsWord(token) OrElse
Me.IsLiteral(token) OrElse
Me.IsOperator(token)
End Function
Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression
Return False
End Function
Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName
Dim simpleName = DirectCast(node, SimpleNameSyntax)
name = simpleName.Identifier.ValueText
arity = simpleName.Arity
End Sub
Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric
Return name.IsKind(SyntaxKind.GenericName)
End Function
Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression
Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)
End Function
Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding
' Member bindings are a C# concept.
Return Nothing
End Function
Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression
' Member bindings are a C# concept.
Return Nothing
End Function
Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression
Dim invocation = TryCast(node, InvocationExpressionSyntax)
If invocation IsNot Nothing Then
expression = invocation?.Expression
argumentList = invocation?.ArgumentList
Return
End If
If node.Kind() = SyntaxKind.DictionaryAccessExpression Then
GetPartsOfMemberAccessExpression(node, expression, argumentList)
Return
End If
Throw ExceptionUtilities.UnexpectedValue(node.Kind())
End Sub
Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation
Return DirectCast(node, InterpolationSyntax).Expression
End Function
Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext
Return SyntaxFacts.IsInNamespaceOrTypeContext(node)
End Function
Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList
Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing
End Function
Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext
Return node.IsInStaticContext()
End Function
Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument
Return DirectCast(node, ArgumentSyntax).GetArgumentExpression()
End Function
Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument
' TODO(cyrusn): Consider the method this argument is passed to, to determine this.
Return RefKind.None
End Function
Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument
Return TypeOf node Is ArgumentSyntax
End Function
Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument
Dim argument = TryCast(node, ArgumentSyntax)
Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted
End Function
Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext
Return node.IsInConstantContext()
End Function
Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor
Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock)
End Function
Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext
Return False
End Function
Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute
Return DirectCast(node, AttributeSyntax).Name
End Function
Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier
Dim identifierName = TryCast(node, IdentifierNameSyntax)
Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso
identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso
identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso
identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute)
End Function
Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration
If root Is Nothing Then
Throw New ArgumentNullException(NameOf(root))
End If
If position < 0 OrElse position > root.Span.End Then
Throw New ArgumentOutOfRangeException(NameOf(position))
End If
Return root.
FindToken(position).
GetAncestors(Of SyntaxNode)().
FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax)
End Function
Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim parent = node.Parent
While node IsNot Nothing
If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then
Return node
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim unused As SyntaxNode = Nothing
Return IsMemberInitializerNamedAssignmentIdentifier(node, unused)
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(
node As SyntaxNode,
ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
' .parent is the NamedField.
' .parent.parent is the ObjectInitializer.
' .parent.parent.parent will be the ObjectCreationExpression.
initializedInstance = identifier.Parent.Parent.Parent
Return True
End If
Return False
End Function
Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern
Return False
End Function
Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause
Return False
End Function
Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression
' VB doesn't have a specialized node for element access. Instead, it just uses an
' invocation expression or dictionary access expression.
Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression
End Function
Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef
Return False
End Function
Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration
Contract.ThrowIfNull(root, NameOf(root))
Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position))
Dim [end] = root.FullSpan.End
If [end] = 0 Then
' empty file
Return Nothing
End If
' make sure position doesn't touch end of root
position = Math.Min(position, [end] - 1)
Dim node = root.FindToken(position).Parent
While node IsNot Nothing
If useFullSpan OrElse node.Span.Contains(position) Then
If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return node
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return node
End If
If TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is FieldDeclarationSyntax Then
Return node
End If
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember
' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and
' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things
' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level
' members.
If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return True
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return True
End If
If TypeOf node Is DeclareStatementSyntax Then
Return True
End If
Return TypeOf node Is ConstructorBlockSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is OperatorBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is FieldDeclarationSyntax
End Function
Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding
Dim member = GetContainingMemberDeclaration(node, node.SpanStart)
If member Is Nothing Then
Return Nothing
End If
' TODO: currently we only support method for now
Dim method = TryCast(member, MethodBlockBaseSyntax)
If method IsNot Nothing Then
If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then
Return Nothing
End If
' We don't want to include the BlockStatement or any trailing trivia up to and including its statement
' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up
' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start
' of the EndBlockStatements leading trivia.
Dim firstStatement = method.Statements.FirstOrDefault()
Dim spanStart = If(firstStatement IsNot Nothing,
firstStatement.FullSpan.Start,
method.EndBlockStatement.FullSpan.Start)
Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart)
End If
Return Nothing
End Function
Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span)
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span)
End If
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span)
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span)
End If
Return False
End Function
Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean
If innerSpan.IsEmpty Then
Return outerSpan.Contains(innerSpan.Start)
End If
Return outerSpan.Contains(innerSpan)
End Function
Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=True, methodLevel:=True)
Return list
End Function
Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=False, methodLevel:=True)
Return list
End Function
Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration
Return DirectCast(typeDeclaration, TypeBlockSyntax).Members
End Function
Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers
Return TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Private Const s_dotToken As String = "."
Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName
If node Is Nothing Then
Return String.Empty
End If
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
' member keyword (if any)
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then
Dim keywordToken = memberDeclaration.GetMemberKeywordToken()
If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then
builder.Append(keywordToken.Text)
builder.Append(" "c)
End If
End If
Dim names = ArrayBuilder(Of String).GetInstance()
' containing type(s)
Dim parent = node.Parent
While TypeOf parent Is TypeBlockSyntax
names.Push(GetName(parent, options, containsGlobalKeyword:=False))
parent = parent.Parent
End While
If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then
' containing namespace(s) in source (if any)
Dim containsGlobalKeyword As Boolean = False
While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock
names.Push(GetName(parent, options, containsGlobalKeyword))
parent = parent.Parent
End While
' root namespace (if any)
If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then
builder.Append(rootNamespace)
builder.Append(s_dotToken)
End If
End If
While Not names.IsEmpty()
Dim name = names.Pop()
If name IsNot Nothing Then
builder.Append(name)
builder.Append(s_dotToken)
End If
End While
names.Free()
' name (include generic type parameters)
builder.Append(GetName(node, options, containsGlobalKeyword:=False))
' parameter list (if any)
If (options And DisplayNameOptions.IncludeParameters) <> 0 Then
builder.Append(memberDeclaration.GetParameterList())
End If
' As clause (if any)
If (options And DisplayNameOptions.IncludeType) <> 0 Then
Dim asClause = memberDeclaration.GetAsClause()
If asClause IsNot Nothing Then
builder.Append(" "c)
builder.Append(asClause)
End If
End If
Return pooled.ToStringAndFree()
End Function
Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String
Const missingTokenPlaceholder As String = "?"
Select Case node.Kind()
Case SyntaxKind.CompilationUnit
Return Nothing
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier
Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text)
Case SyntaxKind.IncompleteMember
Return missingTokenPlaceholder
Case SyntaxKind.NamespaceBlock
Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name
If nameSyntax.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return Nothing
Else
Return GetName(nameSyntax, options, containsGlobalKeyword)
End If
Case SyntaxKind.QualifiedName
Dim qualified = CType(node, QualifiedNameSyntax)
If qualified.Left.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified
Else
Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword)
End If
End Select
Dim name As String = Nothing
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If memberDeclaration IsNot Nothing Then
Dim nameToken = memberDeclaration.GetNameToken()
If nameToken <> Nothing Then
name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text)
If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
builder.Append(name)
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList())
name = pooled.ToStringAndFree()
End If
End If
End If
Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString())
Return name
End Function
Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax)
If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then
builder.Append("(Of ")
builder.Append(typeParameterList.Parameters(0).Identifier.Text)
For i = 1 To typeParameterList.Parameters.Count - 1
builder.Append(", ")
builder.Append(typeParameterList.Parameters(i).Identifier.Text)
Next
builder.Append(")"c)
End If
End Sub
Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean)
Debug.Assert(topLevel OrElse methodLevel)
For Each member In node.GetMembers()
If IsTopLevelNodeWithMembers(member) Then
If topLevel Then
list.Add(member)
End If
AppendMembers(member, list, topLevel, methodLevel)
Continue For
End If
If methodLevel AndAlso IsMethodLevelMember(member) Then
list.Add(member)
End If
Next
End Sub
Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent
Dim node = token.Parent
While node IsNot Nothing
Dim parent = node.Parent
' If this node is on the left side of a member access expression, don't ascend
' further or we'll end up binding to something else.
Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
If memberAccess.Expression Is node Then
Exit While
End If
End If
' If this node is on the left side of a qualified name, don't ascend
' further or we'll end up binding to something else.
Dim qualifiedName = TryCast(parent, QualifiedNameSyntax)
If qualifiedName IsNot Nothing Then
If qualifiedName.Left Is node Then
Exit While
End If
End If
' If this node is the type of an object creation expression, return the
' object creation expression.
Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax)
If objectCreation IsNot Nothing Then
If objectCreation.Type Is node Then
node = parent
Exit While
End If
End If
' The inside of an interpolated string is treated as its own token so we
' need to force navigation to the parent expression syntax.
If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then
node = parent
Exit While
End If
' If this node is not parented by a name, we're done.
Dim name = TryCast(parent, NameSyntax)
If name Is Nothing Then
Exit While
End If
node = parent
End While
Return node
End Function
Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors
Dim compilationUnit = TryCast(root, CompilationUnitSyntax)
If compilationUnit Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim constructors = New List(Of SyntaxNode)()
AppendConstructors(compilationUnit.Members, constructors, cancellationToken)
Return constructors
End Function
Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken)
For Each member As StatementSyntax In members
cancellationToken.ThrowIfCancellationRequested()
Dim constructor = TryCast(member, ConstructorBlockSyntax)
If constructor IsNot Nothing Then
constructors.Add(constructor)
Continue For
End If
Dim [namespace] = TryCast(member, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
AppendConstructors([namespace].Members, constructors, cancellationToken)
End If
Dim [class] = TryCast(member, ClassBlockSyntax)
If [class] IsNot Nothing Then
AppendConstructors([class].Members, constructors, cancellationToken)
End If
Dim [struct] = TryCast(member, StructureBlockSyntax)
If [struct] IsNot Nothing Then
AppendConstructors([struct].Members, constructors, cancellationToken)
End If
Next
End Sub
Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition
Dim trivia = tree.FindTriviaToLeft(position, cancellationToken)
If trivia.Kind = SyntaxKind.DisabledTextTrivia Then
Return trivia.FullSpan
End If
Return Nothing
End Function
Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument
If TryCast(argument, ArgumentSyntax)?.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
End If
Return String.Empty
End Function
Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument
' All argument types are ArgumentSyntax in VB.
Return GetNameForArgument(argument)
End Function
Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot
Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot()
End Function
Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Right,
TryCast(node, MemberAccessExpressionSyntax)?.Name)
End Function
Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Left,
TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget))
End Function
Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier
Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing
End Function
Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement
End Function
Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement
End Function
Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement
End Function
Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment
Return DirectCast(node, AssignmentStatementSyntax).Right
End Function
Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator
Return node.IsKind(SyntaxKind.InferredFieldInitializer)
End Function
Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression
Return False
End Function
Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression
Return False
End Function
Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString
Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value
End Function
Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral
Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral
' VB does not have verbatim strings
Return False
End Function
Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression
Dim argumentList = DirectCast(node, InvocationExpressionSyntax).ArgumentList
Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList))
End Function
Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression
Dim argumentList = DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList
Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList))
End Function
Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList
Return DirectCast(node, ArgumentListSyntax).Arguments
End Function
Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine
Return node.ConvertToSingleLine(useElasticTrivia)
End Function
Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return node.IsKind(SyntaxKind.DocumentationCommentTrivia)
End Function
Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport
Return node.IsKind(SyntaxKind.ImportsStatement)
End Function
Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute
Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword)
End Function
Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute
Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword)
End Function
Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean
If node.IsKind(SyntaxKind.Attribute) Then
Dim attributeNode = CType(node, AttributeSyntax)
If attributeNode.Target IsNot Nothing Then
Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget)
End If
End If
Return False
End Function
Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration
' From the Visual Basic language spec:
' NamespaceMemberDeclaration :=
' NamespaceDeclaration |
' TypeDeclaration
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
' ClassMemberDeclaration ::=
' NonModuleDeclaration |
' EventMemberDeclaration |
' VariableMemberDeclaration |
' ConstantMemberDeclaration |
' MethodMemberDeclaration |
' PropertyMemberDeclaration |
' ConstructorMemberDeclaration |
' OperatorDeclaration
Select Case node.Kind()
' Because fields declarations can define multiple symbols "Public a, b As Integer"
' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
Case SyntaxKind.VariableDeclarator
If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then
Return True
End If
Return False
Case SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumStatement,
SyntaxKind.EnumBlock,
SyntaxKind.StructureStatement,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassStatement,
SyntaxKind.ClassBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EventStatement,
SyntaxKind.EventBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.FieldDeclaration,
SyntaxKind.SubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SubNewStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.OperatorBlock
Return True
End Select
Return False
End Function
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return True
End Select
Return False
End Function
Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement
Return node.IsKind(SyntaxKind.SimpleAssignmentStatement)
End Function
Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement
' VB only has assignment statements, so this can just delegate to that helper
GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right)
End Sub
Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement
Dim assignment = DirectCast(statement, AssignmentStatementSyntax)
left = assignment.Left
operatorToken = assignment.OperatorToken
right = assignment.Right
End Sub
Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName
Return DirectCast(node, SimpleNameSyntax).Identifier
End Function
Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier
End Function
Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter
Return DirectCast(node, ParameterSyntax).Identifier.Identifier
End Function
Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ClassStatement,
SyntaxKind.ModuleStatement
Return DirectCast(node, TypeStatementSyntax).Identifier
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(node, DelegateStatementSyntax).Identifier
End Select
Throw ExceptionUtilities.UnexpectedValue(node)
End Function
Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName
Return DirectCast(node, IdentifierNameSyntax).Identifier
End Function
Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement
Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators.
Contains(DirectCast(declarator, VariableDeclaratorSyntax))
End Function
Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(token1, token2)
End Function
Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(node1, node2)
End Function
Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach
Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node
End Function
Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement
Return DirectCast(node, ExpressionStatementSyntax).Expression
End Function
Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression
Return node.IsKind(SyntaxKind.TypeOfIsExpression)
End Function
Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses
Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node)
End Function
Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression
Dim tupleExpr = DirectCast(node, TupleExpressionSyntax)
openParen = tupleExpr.OpenParenToken
arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax))
closeParen = tupleExpr.CloseParenToken
End Sub
Private Function ISyntaxFacts_IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineCommentTrivia
Return MyBase.IsSingleLineCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineCommentTrivia
Return MyBase.IsMultiLineCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineDocCommentTrivia
Return MyBase.IsSingleLineDocCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineDocCommentTrivia
Return MyBase.IsMultiLineDocCommentTrivia(trivia)
Return False
End Function
Private Function ISyntaxFacts_IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsShebangDirectiveTrivia
Return MyBase.IsShebangDirectiveTrivia(trivia)
End Function
Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsPreprocessorDirective
Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind())
End Function
Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic
Return trivia.IsElastic()
End Function
Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective
Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes)
End Function
Public Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return token.ContainsInterleavedDirective(span, cancellationToken)
End Function
Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia
Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia
End Function
Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers
Return node.GetModifiers()
End Function
Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers
Return node.WithModifiers(modifiers)
End Function
Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement
Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators
End Function
Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Initializer
End Function
Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type
End Function
Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause
Return DirectCast(node, EqualsValueSyntax).Value
End Function
Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock
' VB has no equivalent of curly braces.
Return False
End Function
Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock
Return node.IsExecutableBlock()
End Function
Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements
Return node.GetExecutableBlockStatements()
End Function
Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock
Return nodes.FindInnermostCommonExecutableBlock()
End Function
Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer
Return IsExecutableBlock(node)
End Function
Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements
Return GetExecutableBlockStatements(node)
End Function
Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression
Return node.Kind = SyntaxKind.CTypeExpression
End Function
Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression
Return node.Kind = SyntaxKind.DirectCastExpression
End Function
Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression
Dim cast = DirectCast(node, DirectCastExpressionSyntax)
type = cast.Type
expression = cast.Expression
End Sub
Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation
Throw New NotImplementedException()
End Function
Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride
If token.Kind() = SyntaxKind.OverridesKeyword Then
Dim parent = token.Parent
Select Case parent.Kind()
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(parent, MethodStatementSyntax)
Return method.Identifier
Case SyntaxKind.PropertyStatement
Dim [property] = DirectCast(parent, PropertyStatementSyntax)
Return [property].Identifier
End Select
End If
Return Nothing
End Function
Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression
' Does not exist in VB.
Return False
End Function
Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists
Return node.GetAttributeLists()
End Function
Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective
Dim importStatement = TryCast(node, ImportsStatementSyntax)
If (importStatement IsNot Nothing) Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
Return True
End If
End If
Next
End If
Return False
End Function
Public Sub GetPartsOfUsingAliasDirective(
node As SyntaxNode,
ByRef globalKeyword As SyntaxToken,
ByRef [alias] As SyntaxToken,
ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUsingAliasDirective
Dim importStatement = DirectCast(node, ImportsStatementSyntax)
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
globalKeyword = Nothing
[alias] = simpleImportsClause.Alias.Identifier
name = simpleImportsClause.Name
Return
End If
End If
Next
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax
Dim xmlElement = TryCast(node, XmlElementSyntax)
If xmlElement IsNot Nothing Then
Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax)
Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName
End If
Return False
End Function
Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax
Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax)
If documentationCommentTrivia IsNot Nothing Then
Return documentationCommentTrivia.Content
End If
Return Nothing
End Function
Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind)
End Function
Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean
Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement)
End Function
Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer
Dim count As Integer = 0
For i = 0 To nodes.Count - 1
count = count + GetDeclarationCount(nodes(i))
Next
Return count
End Function
Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer
Select Case node.Kind
Case SyntaxKind.FieldDeclaration
Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators)
Case SyntaxKind.LocalDeclarationStatement
Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators)
Case SyntaxKind.VariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Count
Case SyntaxKind.AttributesStatement
Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists)
Case SyntaxKind.AttributeList
Return DirectCast(node, AttributeListSyntax).Attributes.Count
Case SyntaxKind.ImportsStatement
Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count
End Select
Return 1
End Function
Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern
Return False
End Function
Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression
Return False
End Function
Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern
Return False
End Function
Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern
Return False
End Function
Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern
Return False
End Function
Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern
Return False
End Function
Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern
Return False
End Function
Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern
Return False
End Function
Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern
Return False
End Function
Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern
Return False
End Function
Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern
Return False
End Function
Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern
Return False
End Function
Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern
Return False
End Function
Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern
Return False
End Function
Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression
Throw ExceptionUtilities.Unreachable
End Sub
Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern
Throw ExceptionUtilities.Unreachable
End Function
Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern
Throw New NotImplementedException()
End Sub
Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern
Throw New NotImplementedException()
End Sub
Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern
Throw New NotImplementedException()
End Function
Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression
Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax)
stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken
contents = interpolatedStringExpressionSyntax.Contents
stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken
End Sub
Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression
Return False
End Function
#Region "IsXXX members"
Public Function IsAnonymousFunctionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunctionExpression
Return TypeOf node Is LambdaExpressionSyntax
End Function
Public Function IsBaseNamespaceDeclaration(<NotNullWhen(True)> node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseNamespaceDeclaration
Return TypeOf node Is NamespaceBlockSyntax
End Function
Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression
Return TypeOf node Is BinaryExpressionSyntax
End Function
Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression
Return TypeOf node Is LiteralExpressionSyntax
End Function
Public Function IsMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberAccessExpression
Return TypeOf node Is MemberAccessExpressionSyntax
End Function
Public Function IsSimpleName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleName
Return TypeOf node Is SimpleNameSyntax
End Function
#End Region
#Region "GetPartsOfXXX members"
Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression
Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax)
left = binaryExpression.Left
operatorToken = binaryExpression.OperatorToken
right = binaryExpression.Right
End Sub
Public Sub GetPartsOfCompilationUnit(node As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef attributeLists As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfCompilationUnit
Dim compilationUnit = DirectCast(node, CompilationUnitSyntax)
[imports] = compilationUnit.Imports
attributeLists = compilationUnit.Attributes
members = compilationUnit.Members
End Sub
Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression
Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax)
expression = conditionalAccess.Expression
operatorToken = conditionalAccess.QuestionMarkToken
whenNotNull = conditionalAccess.WhenNotNull
End Sub
Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression
Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax)
condition = conditionalExpression.Condition
whenTrue = conditionalExpression.WhenTrue
whenFalse = conditionalExpression.WhenFalse
End Sub
Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression
Dim invocation = DirectCast(node, InvocationExpressionSyntax)
expression = invocation.Expression
argumentList = invocation.ArgumentList
End Sub
Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression
Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax)
expression = memberAccess.Expression
operatorToken = memberAccess.OperatorToken
name = memberAccess.Name
End Sub
Public Sub GetPartsOfBaseNamespaceDeclaration(node As SyntaxNode, ByRef name As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfBaseNamespaceDeclaration
Dim namespaceBlock = DirectCast(node, NamespaceBlockSyntax)
name = namespaceBlock.NamespaceStatement.Name
[imports] = Nothing
members = namespaceBlock.Members
End Sub
Public Sub GetPartsOfObjectCreationExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef argumentList As SyntaxNode, ByRef initializer As SyntaxNode) Implements ISyntaxFacts.GetPartsOfObjectCreationExpression
Dim objectCreationExpression = DirectCast(node, ObjectCreationExpressionSyntax)
type = objectCreationExpression.Type
argumentList = objectCreationExpression.ArgumentList
initializer = objectCreationExpression.Initializer
End Sub
Public Sub GetPartsOfParenthesizedExpression(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression
Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax)
openParen = parenthesizedExpression.OpenParenToken
expression = parenthesizedExpression.Expression
closeParen = parenthesizedExpression.CloseParenToken
End Sub
Public Sub GetPartsOfPrefixUnaryExpression(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef operand As SyntaxNode) Implements ISyntaxFacts.GetPartsOfPrefixUnaryExpression
Dim unaryExpression = DirectCast(node, UnaryExpressionSyntax)
operatorToken = unaryExpression.OperatorToken
operand = unaryExpression.Operand
End Sub
Public Sub GetPartsOfQualifiedName(node As SyntaxNode, ByRef left As SyntaxNode, ByRef dotToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfQualifiedName
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
left = qualifiedName.Left
dotToken = qualifiedName.DotToken
right = qualifiedName.Right
End Sub
#End Region
#Region "GetXXXOfYYY members"
Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).Expression
End Function
Public Function GetExpressionOfThrowExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression
' ThrowExpression doesn't exist in VB
Throw New NotImplementedException()
End Function
#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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports System.Diagnostics.CodeAnalysis
#If CODE_STYLE Then
Imports Microsoft.CodeAnalysis.Internal.Editing
#Else
Imports Microsoft.CodeAnalysis.Editing
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Friend Class VisualBasicSyntaxFacts
Inherits AbstractSyntaxFacts
Implements ISyntaxFacts
Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts
Protected Sub New()
End Sub
Public Overrides ReadOnly Property IsCaseSensitive As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property StringComparer As StringComparer
Get
Return CaseInsensitiveComparison.Comparer
End Get
End Property
Public Overrides ReadOnly Property ElasticMarker As SyntaxTrivia
Get
Return SyntaxFactory.ElasticMarker
End Get
End Property
Public Overrides ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia
Get
Return SyntaxFactory.ElasticCarriageReturnLineFeed
End Get
End Property
Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance
Public Overrides Function SupportsIndexingInitializer(options As ParseOptions) As Boolean
Return False
End Function
Public Overrides Function SupportsThrowExpression(options As ParseOptions) As Boolean
Return False
End Function
Public Overrides Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean
Return False
End Function
Public Overrides Function SupportsRecord(options As ParseOptions) As Boolean
Return False
End Function
Public Overrides Function SupportsRecordStruct(options As ParseOptions) As Boolean
Return False
End Function
Public Overrides Function ParseToken(text As String) As SyntaxToken
Return SyntaxFactory.ParseToken(text, startStatement:=True)
End Function
Public Overrides Function ParseLeadingTrivia(text As String) As SyntaxTriviaList
Return SyntaxFactory.ParseLeadingTrivia(text)
End Function
Public Overrides Function EscapeIdentifier(identifier As String) As String
Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier)
Dim needsEscaping = keywordKind <> SyntaxKind.None
Return If(needsEscaping, "[" & identifier & "]", identifier)
End Function
Public Overrides Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean
Return False
End Function
Public Overrides Function IsOperator(token As SyntaxToken) As Boolean
Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse
(IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax))
End Function
Public Overrides Function IsContextualKeyword(token As SyntaxToken) As Boolean
Return token.IsContextualKeyword()
End Function
Public Overrides Function IsReservedKeyword(token As SyntaxToken) As Boolean
Return token.IsReservedKeyword()
End Function
Public Overrides Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean
Return token.IsPreprocessorKeyword()
End Function
Public Overrides Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)
End Function
Public Overrides Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean
If token.Kind = SyntaxKind.CloseBraceToken Then
Dim tuples = token.Parent.GetBraces()
openBrace = tuples.openBrace
Return openBrace.Kind = SyntaxKind.OpenBraceToken
End If
Return False
End Function
Public Overrides Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken)
End Function
Public Overrides Function IsDirective(node As SyntaxNode) As Boolean
Return TypeOf node Is DirectiveTriviaSyntax
End Function
Public Overrides Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean
Select Case node.Kind
Case SyntaxKind.ExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False)
Return True
Case SyntaxKind.EndExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(Nothing, True)
Return True
End Select
Return False
End Function
Public Overrides Function IsDeclarationExpression(node As SyntaxNode) As Boolean
' VB doesn't support declaration expressions
Return False
End Function
Public Overrides Function IsAttributeName(node As SyntaxNode) As Boolean
Return node.IsParentKind(SyntaxKind.Attribute) AndAlso
DirectCast(node.Parent, AttributeSyntax).Name Is node
End Function
Public Overrides Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean
Dim vbNode = TryCast(node, ExpressionSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName()
End Function
Public Overrides Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean
Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax)
Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node
End Function
Public Overrides Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode
Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax))
End Function
Public Overrides Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode
Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression()
End Function
Public Overrides Function IsNamedArgument(node As SyntaxNode) As Boolean
Dim arg = TryCast(node, SimpleArgumentSyntax)
Return arg?.NameColonEquals IsNot Nothing
End Function
Public Overrides Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean
Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node)
End Function
Public Overrides Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken?
Return DirectCast(node, ParameterSyntax).Identifier?.Identifier
End Function
Public Overrides Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode
Return DirectCast(node, ParameterSyntax).Default
End Function
Public Overrides Function GetParameterList(node As SyntaxNode) As SyntaxNode
Return node.GetParameterList()
End Function
Public Overrides Function IsParameterList(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.ParameterList)
End Function
Public Overrides Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken
Return DirectCast(genericName, GenericNameSyntax).Identifier
End Function
Public Overrides Function IsUsingDirectiveName(node As SyntaxNode) As Boolean
Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso
DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node
End Function
Public Overrides Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsStatement(node As SyntaxNode) As Boolean
Return TypeOf node Is StatementSyntax
End Function
Public Overrides Function IsExecutableStatement(node As SyntaxNode) As Boolean
Return TypeOf node Is ExecutableStatementSyntax
End Function
Public Overrides Function IsMethodBody(node As SyntaxNode) As Boolean
Return TypeOf node Is MethodBlockBaseSyntax
End Function
Public Overrides Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode
Return DirectCast(node, ReturnStatementSyntax).Expression
End Function
Public Overrides Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsThisConstructorInitializer()
End If
Return False
End Function
Public Overrides Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsBaseConstructorInitializer()
End If
Return False
End Function
Public Overrides Function IsQueryKeyword(token As SyntaxToken) As Boolean
Select Case token.Kind()
Case _
SyntaxKind.JoinKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.AggregateKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.SelectKeyword
Return TypeOf token.Parent Is QueryClauseSyntax
Case SyntaxKind.GroupKeyword
Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation))
Case SyntaxKind.EqualsKeyword
Return TypeOf token.Parent Is JoinConditionSyntax
Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword
Return TypeOf token.Parent Is OrderingSyntax
Case SyntaxKind.InKeyword
Return TypeOf token.Parent Is CollectionRangeVariableSyntax
Case Else
Return False
End Select
End Function
Public Overrides Function IsPredefinedType(token As SyntaxToken) As Boolean
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None
End Function
Public Overrides Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType = type
End Function
Public Overrides Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean
type = GetPredefinedType(token)
Return type <> PredefinedType.None
End Function
Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType
Select Case token.Kind
Case SyntaxKind.BooleanKeyword
Return PredefinedType.Boolean
Case SyntaxKind.ByteKeyword
Return PredefinedType.Byte
Case SyntaxKind.SByteKeyword
Return PredefinedType.SByte
Case SyntaxKind.IntegerKeyword
Return PredefinedType.Int32
Case SyntaxKind.UIntegerKeyword
Return PredefinedType.UInt32
Case SyntaxKind.ShortKeyword
Return PredefinedType.Int16
Case SyntaxKind.UShortKeyword
Return PredefinedType.UInt16
Case SyntaxKind.LongKeyword
Return PredefinedType.Int64
Case SyntaxKind.ULongKeyword
Return PredefinedType.UInt64
Case SyntaxKind.SingleKeyword
Return PredefinedType.Single
Case SyntaxKind.DoubleKeyword
Return PredefinedType.Double
Case SyntaxKind.DecimalKeyword
Return PredefinedType.Decimal
Case SyntaxKind.StringKeyword
Return PredefinedType.String
Case SyntaxKind.CharKeyword
Return PredefinedType.Char
Case SyntaxKind.ObjectKeyword
Return PredefinedType.Object
Case SyntaxKind.DateKeyword
Return PredefinedType.DateTime
Case Else
Return PredefinedType.None
End Select
End Function
Public Overrides Function IsPredefinedOperator(token As SyntaxToken) As Boolean
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None
End Function
Public Overrides Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op
End Function
Public Overrides Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean
op = GetPredefinedOperator(token)
Return op <> PredefinedOperator.None
End Function
Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator
Select Case token.Kind
Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken
Return PredefinedOperator.Addition
Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken
Return PredefinedOperator.Subtraction
Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword
Return PredefinedOperator.BitwiseAnd
Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword
Return PredefinedOperator.BitwiseOr
Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken
Return PredefinedOperator.Concatenate
Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken
Return PredefinedOperator.Division
Case SyntaxKind.EqualsToken
Return PredefinedOperator.Equality
Case SyntaxKind.XorKeyword
Return PredefinedOperator.ExclusiveOr
Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken
Return PredefinedOperator.Exponent
Case SyntaxKind.GreaterThanToken
Return PredefinedOperator.GreaterThan
Case SyntaxKind.GreaterThanEqualsToken
Return PredefinedOperator.GreaterThanOrEqual
Case SyntaxKind.LessThanGreaterThanToken
Return PredefinedOperator.Inequality
Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken
Return PredefinedOperator.IntegerDivision
Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken
Return PredefinedOperator.LeftShift
Case SyntaxKind.LessThanToken
Return PredefinedOperator.LessThan
Case SyntaxKind.LessThanEqualsToken
Return PredefinedOperator.LessThanOrEqual
Case SyntaxKind.LikeKeyword
Return PredefinedOperator.Like
Case SyntaxKind.NotKeyword
Return PredefinedOperator.Complement
Case SyntaxKind.ModKeyword
Return PredefinedOperator.Modulus
Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken
Return PredefinedOperator.Multiplication
Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken
Return PredefinedOperator.RightShift
Case Else
Return PredefinedOperator.None
End Select
End Function
Public Overrides Function GetText(kind As Integer) As String
Return SyntaxFacts.GetText(CType(kind, SyntaxKind))
End Function
Public Overrides Function IsIdentifierPartCharacter(c As Char) As Boolean
Return SyntaxFacts.IsIdentifierPartCharacter(c)
End Function
Public Overrides Function IsIdentifierStartCharacter(c As Char) As Boolean
Return SyntaxFacts.IsIdentifierStartCharacter(c)
End Function
Public Overrides Function IsIdentifierEscapeCharacter(c As Char) As Boolean
Return c = "["c OrElse c = "]"c
End Function
Public Overrides Function IsValidIdentifier(identifier As String) As Boolean
Dim token = SyntaxFactory.ParseToken(identifier)
' TODO: There is no way to get the diagnostics to see if any are actually errors?
Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length
End Function
Public Overrides Function IsVerbatimIdentifier(identifier As String) As Boolean
Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]"
End Function
Public Overrides Function IsTypeCharacter(c As Char) As Boolean
Return c = "%"c OrElse
c = "&"c OrElse
c = "@"c OrElse
c = "!"c OrElse
c = "#"c OrElse
c = "$"c
End Function
Public Overrides Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean
Return False ' VB does not support identifiers with escaped unicode characters
End Function
Public Overrides Function IsLiteral(token As SyntaxToken) As Boolean
Select Case token.Kind()
Case _
SyntaxKind.IntegerLiteralToken,
SyntaxKind.CharacterLiteralToken,
SyntaxKind.DecimalLiteralToken,
SyntaxKind.FloatingLiteralToken,
SyntaxKind.DateLiteralToken,
SyntaxKind.StringLiteralToken,
SyntaxKind.DollarSignDoubleQuoteToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.InterpolatedStringTextToken,
SyntaxKind.TrueKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.NothingKeyword
Return True
End Select
Return False
End Function
Public Overrides Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean
Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken)
End Function
Public Overrides Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean
Return Me.IsWord(token) OrElse
Me.IsLiteral(token) OrElse
Me.IsOperator(token)
End Function
Public Overrides Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer)
Dim simpleName = DirectCast(node, SimpleNameSyntax)
name = simpleName.Identifier.ValueText
arity = simpleName.Arity
End Sub
Public Overrides Function LooksGeneric(name As SyntaxNode) As Boolean
Return name.IsKind(SyntaxKind.GenericName)
End Function
Public Overrides Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode
Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)
End Function
Public Overrides Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode
' Member bindings are a C# concept.
Return Nothing
End Function
Public Overrides Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode
' Member bindings are a C# concept.
Return Nothing
End Function
Public Overrides Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode)
Dim invocation = TryCast(node, InvocationExpressionSyntax)
If invocation IsNot Nothing Then
expression = invocation?.Expression
argumentList = invocation?.ArgumentList
Return
End If
If node.Kind() = SyntaxKind.DictionaryAccessExpression Then
GetPartsOfMemberAccessExpression(node, expression, argumentList)
Return
End If
Throw ExceptionUtilities.UnexpectedValue(node.Kind())
End Sub
Public Overrides Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode
Return DirectCast(node, InterpolationSyntax).Expression
End Function
Public Overrides Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean
Return SyntaxFacts.IsInNamespaceOrTypeContext(node)
End Function
Public Overrides Function IsBaseTypeList(node As SyntaxNode) As Boolean
Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing
End Function
Public Overrides Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean
Return node.IsInStaticContext()
End Function
Public Overrides Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode
Return DirectCast(node, ArgumentSyntax).GetArgumentExpression()
End Function
Public Overrides Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind
' TODO(cyrusn): Consider the method this argument is passed to, to determine this.
Return RefKind.None
End Function
Public Overrides Function IsArgument(node As SyntaxNode) As Boolean
Return TypeOf node Is ArgumentSyntax
End Function
Public Overrides Function IsSimpleArgument(node As SyntaxNode) As Boolean
Dim argument = TryCast(node, ArgumentSyntax)
Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted
End Function
Public Overrides Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean
Return node.IsInConstantContext()
End Function
Public Overrides Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean
Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock)
End Function
Public Overrides Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode
Return DirectCast(node, AttributeSyntax).Name
End Function
Public Overrides Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean
Dim identifierName = TryCast(node, IdentifierNameSyntax)
Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso
identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso
identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso
identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute)
End Function
Public Overrides Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode
If root Is Nothing Then
Throw New ArgumentNullException(NameOf(root))
End If
If position < 0 OrElse position > root.Span.End Then
Throw New ArgumentOutOfRangeException(NameOf(position))
End If
Return root.
FindToken(position).
GetAncestors(Of SyntaxNode)().
FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax)
End Function
Public Overrides Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim parent = node.Parent
While node IsNot Nothing
If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then
Return node
End If
node = node.Parent
End While
Return Nothing
End Function
Public Overrides Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean
Dim unused As SyntaxNode = Nothing
Return IsMemberInitializerNamedAssignmentIdentifier(node, unused)
End Function
Public Overrides Function IsMemberInitializerNamedAssignmentIdentifier(
node As SyntaxNode,
ByRef initializedInstance As SyntaxNode) As Boolean
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
' .parent is the NamedField.
' .parent.parent is the ObjectInitializer.
' .parent.parent.parent will be the ObjectCreationExpression.
initializedInstance = identifier.Parent.Parent.Parent
Return True
End If
Return False
End Function
Public Overrides Function IsNameOfSubpattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsPropertyPatternClause(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsElementAccessExpression(node As SyntaxNode) As Boolean
' VB doesn't have a specialized node for element access. Instead, it just uses an
' invocation expression or dictionary access expression.
Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression
End Function
Public Overrides Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode
Contract.ThrowIfNull(root, NameOf(root))
Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position))
Dim [end] = root.FullSpan.End
If [end] = 0 Then
' empty file
Return Nothing
End If
' make sure position doesn't touch end of root
position = Math.Min(position, [end] - 1)
Dim node = root.FindToken(position).Parent
While node IsNot Nothing
If useFullSpan OrElse node.Span.Contains(position) Then
If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return node
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return node
End If
If TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is FieldDeclarationSyntax Then
Return node
End If
End If
node = node.Parent
End While
Return Nothing
End Function
Public Overrides Function IsMethodLevelMember(node As SyntaxNode) As Boolean
' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and
' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things
' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level
' members.
If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return True
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return True
End If
If TypeOf node Is DeclareStatementSyntax Then
Return True
End If
Return TypeOf node Is ConstructorBlockSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is OperatorBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is FieldDeclarationSyntax
End Function
Public Overrides Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan
Dim member = GetContainingMemberDeclaration(node, node.SpanStart)
If member Is Nothing Then
Return Nothing
End If
' TODO: currently we only support method for now
Dim method = TryCast(member, MethodBlockBaseSyntax)
If method IsNot Nothing Then
If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then
Return Nothing
End If
' We don't want to include the BlockStatement or any trailing trivia up to and including its statement
' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up
' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start
' of the EndBlockStatements leading trivia.
Dim firstStatement = method.Statements.FirstOrDefault()
Dim spanStart = If(firstStatement IsNot Nothing,
firstStatement.FullSpan.Start,
method.EndBlockStatement.FullSpan.Start)
Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart)
End If
Return Nothing
End Function
Public Overrides Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span)
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span)
End If
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span)
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span)
End If
Return False
End Function
Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean
If innerSpan.IsEmpty Then
Return outerSpan.Contains(innerSpan.Start)
End If
Return outerSpan.Contains(innerSpan)
End Function
Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Public Overrides Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode)
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=True, methodLevel:=True)
Return list
End Function
Public Overrides Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode)
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=False, methodLevel:=True)
Return list
End Function
Public Overrides Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode)
Return DirectCast(typeDeclaration, TypeBlockSyntax).Members
End Function
Public Overrides Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean
Return TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Private Const s_dotToken As String = "."
Public Overrides Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String
If node Is Nothing Then
Return String.Empty
End If
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
' member keyword (if any)
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then
Dim keywordToken = memberDeclaration.GetMemberKeywordToken()
If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then
builder.Append(keywordToken.Text)
builder.Append(" "c)
End If
End If
Dim names = ArrayBuilder(Of String).GetInstance()
' containing type(s)
Dim parent = node.Parent
While TypeOf parent Is TypeBlockSyntax
names.Push(GetName(parent, options, containsGlobalKeyword:=False))
parent = parent.Parent
End While
If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then
' containing namespace(s) in source (if any)
Dim containsGlobalKeyword As Boolean = False
While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock
names.Push(GetName(parent, options, containsGlobalKeyword))
parent = parent.Parent
End While
' root namespace (if any)
If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then
builder.Append(rootNamespace)
builder.Append(s_dotToken)
End If
End If
While Not names.IsEmpty()
Dim name = names.Pop()
If name IsNot Nothing Then
builder.Append(name)
builder.Append(s_dotToken)
End If
End While
names.Free()
' name (include generic type parameters)
builder.Append(GetName(node, options, containsGlobalKeyword:=False))
' parameter list (if any)
If (options And DisplayNameOptions.IncludeParameters) <> 0 Then
builder.Append(memberDeclaration.GetParameterList())
End If
' As clause (if any)
If (options And DisplayNameOptions.IncludeType) <> 0 Then
Dim asClause = memberDeclaration.GetAsClause()
If asClause IsNot Nothing Then
builder.Append(" "c)
builder.Append(asClause)
End If
End If
Return pooled.ToStringAndFree()
End Function
Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String
Const missingTokenPlaceholder As String = "?"
Select Case node.Kind()
Case SyntaxKind.CompilationUnit
Return Nothing
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier
Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text)
Case SyntaxKind.IncompleteMember
Return missingTokenPlaceholder
Case SyntaxKind.NamespaceBlock
Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name
If nameSyntax.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return Nothing
Else
Return GetName(nameSyntax, options, containsGlobalKeyword)
End If
Case SyntaxKind.QualifiedName
Dim qualified = CType(node, QualifiedNameSyntax)
If qualified.Left.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified
Else
Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword)
End If
End Select
Dim name As String = Nothing
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If memberDeclaration IsNot Nothing Then
Dim nameToken = memberDeclaration.GetNameToken()
If nameToken <> Nothing Then
name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text)
If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
builder.Append(name)
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList())
name = pooled.ToStringAndFree()
End If
End If
End If
Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString())
Return name
End Function
Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax)
If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then
builder.Append("(Of ")
builder.Append(typeParameterList.Parameters(0).Identifier.Text)
For i = 1 To typeParameterList.Parameters.Count - 1
builder.Append(", ")
builder.Append(typeParameterList.Parameters(i).Identifier.Text)
Next
builder.Append(")"c)
End If
End Sub
Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean)
Debug.Assert(topLevel OrElse methodLevel)
For Each member In node.GetMembers()
If IsTopLevelNodeWithMembers(member) Then
If topLevel Then
list.Add(member)
End If
AppendMembers(member, list, topLevel, methodLevel)
Continue For
End If
If methodLevel AndAlso IsMethodLevelMember(member) Then
list.Add(member)
End If
Next
End Sub
Public Overrides Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode
Dim node = token.Parent
While node IsNot Nothing
Dim parent = node.Parent
' If this node is on the left side of a member access expression, don't ascend
' further or we'll end up binding to something else.
Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
If memberAccess.Expression Is node Then
Exit While
End If
End If
' If this node is on the left side of a qualified name, don't ascend
' further or we'll end up binding to something else.
Dim qualifiedName = TryCast(parent, QualifiedNameSyntax)
If qualifiedName IsNot Nothing Then
If qualifiedName.Left Is node Then
Exit While
End If
End If
' If this node is the type of an object creation expression, return the
' object creation expression.
Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax)
If objectCreation IsNot Nothing Then
If objectCreation.Type Is node Then
node = parent
Exit While
End If
End If
' The inside of an interpolated string is treated as its own token so we
' need to force navigation to the parent expression syntax.
If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then
node = parent
Exit While
End If
' If this node is not parented by a name, we're done.
Dim name = TryCast(parent, NameSyntax)
If name Is Nothing Then
Exit While
End If
node = parent
End While
Return node
End Function
Public Overrides Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode)
Dim compilationUnit = TryCast(root, CompilationUnitSyntax)
If compilationUnit Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim constructors = New List(Of SyntaxNode)()
AppendConstructors(compilationUnit.Members, constructors, cancellationToken)
Return constructors
End Function
Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken)
For Each member As StatementSyntax In members
cancellationToken.ThrowIfCancellationRequested()
Dim constructor = TryCast(member, ConstructorBlockSyntax)
If constructor IsNot Nothing Then
constructors.Add(constructor)
Continue For
End If
Dim [namespace] = TryCast(member, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
AppendConstructors([namespace].Members, constructors, cancellationToken)
End If
Dim [class] = TryCast(member, ClassBlockSyntax)
If [class] IsNot Nothing Then
AppendConstructors([class].Members, constructors, cancellationToken)
End If
Dim [struct] = TryCast(member, StructureBlockSyntax)
If [struct] IsNot Nothing Then
AppendConstructors([struct].Members, constructors, cancellationToken)
End If
Next
End Sub
Public Overrides Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan
Dim trivia = tree.FindTriviaToLeft(position, cancellationToken)
If trivia.Kind = SyntaxKind.DisabledTextTrivia Then
Return trivia.FullSpan
End If
Return Nothing
End Function
Public Overrides Function GetNameForArgument(argument As SyntaxNode) As String
If TryCast(argument, ArgumentSyntax)?.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
End If
Return String.Empty
End Function
Public Overrides Function GetNameForAttributeArgument(argument As SyntaxNode) As String
' All argument types are ArgumentSyntax in VB.
Return GetNameForArgument(argument)
End Function
Public Overrides Function IsLeftSideOfDot(node As SyntaxNode) As Boolean
Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot()
End Function
Public Overrides Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode
Return If(TryCast(node, QualifiedNameSyntax)?.Right,
TryCast(node, MemberAccessExpressionSyntax)?.Name)
End Function
Public Overrides Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode
Return If(TryCast(node, QualifiedNameSyntax)?.Left,
TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget))
End Function
Public Overrides Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean
Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing
End Function
Public Overrides Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean
Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement
End Function
Public Overrides Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean
Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement
End Function
Public Overrides Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean
Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement
End Function
Public Overrides Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode
Return DirectCast(node, AssignmentStatementSyntax).Right
End Function
Public Overrides Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.InferredFieldInitializer)
End Function
Public Overrides Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode)
Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value
End Function
Public Overrides Function IsNumericLiteral(token As SyntaxToken) As Boolean
Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
Public Overrides Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean
' VB does not have verbatim strings
Return False
End Function
Public Overrides Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode)
Dim argumentList = DirectCast(node, InvocationExpressionSyntax).ArgumentList
Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList))
End Function
Public Overrides Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode)
Dim argumentList = DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList
Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList))
End Function
Public Overrides Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode)
Return DirectCast(node, ArgumentListSyntax).Arguments
End Function
Public Overrides Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode
Return node.ConvertToSingleLine(useElasticTrivia)
End Function
Public Overrides Function IsDocumentationComment(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.DocumentationCommentTrivia)
End Function
Public Overrides Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.ImportsStatement)
End Function
Public Overrides Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean
Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword)
End Function
Public Overrides Function IsGlobalModuleAttribute(node As SyntaxNode) As Boolean
Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword)
End Function
Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean
If node.IsKind(SyntaxKind.Attribute) Then
Dim attributeNode = CType(node, AttributeSyntax)
If attributeNode.Target IsNot Nothing Then
Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget)
End If
End If
Return False
End Function
Public Overrides Function IsDeclaration(node As SyntaxNode) As Boolean
' From the Visual Basic language spec:
' NamespaceMemberDeclaration :=
' NamespaceDeclaration |
' TypeDeclaration
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
' ClassMemberDeclaration ::=
' NonModuleDeclaration |
' EventMemberDeclaration |
' VariableMemberDeclaration |
' ConstantMemberDeclaration |
' MethodMemberDeclaration |
' PropertyMemberDeclaration |
' ConstructorMemberDeclaration |
' OperatorDeclaration
Select Case node.Kind()
' Because fields declarations can define multiple symbols "Public a, b As Integer"
' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
Case SyntaxKind.VariableDeclarator
If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then
Return True
End If
Return False
Case SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumStatement,
SyntaxKind.EnumBlock,
SyntaxKind.StructureStatement,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassStatement,
SyntaxKind.ClassBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EventStatement,
SyntaxKind.EventBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.FieldDeclaration,
SyntaxKind.SubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SubNewStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.OperatorBlock
Return True
End Select
Return False
End Function
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
Public Overrides Function IsTypeDeclaration(node As SyntaxNode) As Boolean
Select Case node.Kind()
Case SyntaxKind.EnumBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return True
End Select
Return False
End Function
Public Overrides Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.SimpleAssignmentStatement)
End Function
Public Overrides Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode)
' VB only has assignment statements, so this can just delegate to that helper
GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right)
End Sub
Public Overrides Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode)
Dim assignment = DirectCast(statement, AssignmentStatementSyntax)
left = assignment.Left
operatorToken = assignment.OperatorToken
right = assignment.Right
End Sub
Public Overrides Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken
Return DirectCast(node, SimpleNameSyntax).Identifier
End Function
Public Overrides Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken
Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier
End Function
Public Overrides Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken
Return DirectCast(node, ParameterSyntax).Identifier.Identifier
End Function
Public Overrides Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken
Select Case node.Kind()
Case SyntaxKind.EnumStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ClassStatement,
SyntaxKind.ModuleStatement
Return DirectCast(node, TypeStatementSyntax).Identifier
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(node, DelegateStatementSyntax).Identifier
End Select
Throw ExceptionUtilities.UnexpectedValue(node)
End Function
Public Overrides Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken
Return DirectCast(node, IdentifierNameSyntax).Identifier
End Function
Public Overrides Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean
Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators.
Contains(DirectCast(declarator, VariableDeclaratorSyntax))
End Function
Public Overrides Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean
Return SyntaxFactory.AreEquivalent(token1, token2)
End Function
Public Overrides Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean
Return SyntaxFactory.AreEquivalent(node1, node2)
End Function
Public Overrides Function IsExpressionOfForeach(node As SyntaxNode) As Boolean
Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node
End Function
Public Overrides Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode
Return DirectCast(node, ExpressionStatementSyntax).Expression
End Function
Public Overrides Function IsIsExpression(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.TypeOfIsExpression)
End Function
Public Overrides Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode
Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node)
End Function
Public Overrides Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken)
Dim tupleExpr = DirectCast(node, TupleExpressionSyntax)
openParen = tupleExpr.OpenParenToken
arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax))
closeParen = tupleExpr.CloseParenToken
End Sub
Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean
Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind())
End Function
Public Overrides Function IsRegularComment(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Overrides Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Overrides Function IsElastic(trivia As SyntaxTrivia) As Boolean
Return trivia.IsElastic()
End Function
Public Overrides Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean
Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes)
End Function
Public Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean
Return token.ContainsInterleavedDirective(span, cancellationToken)
End Function
Public Overrides Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean
Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia
End Function
Public Overrides Function GetModifiers(node As SyntaxNode) As SyntaxTokenList
Return node.GetModifiers()
End Function
Public Overrides Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode
Return node.WithModifiers(modifiers)
End Function
Public Overrides Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode)
Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators
End Function
Public Overrides Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode
Return DirectCast(node, VariableDeclaratorSyntax).Initializer
End Function
Public Overrides Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type
End Function
Public Overrides Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode
Return DirectCast(node, EqualsValueSyntax).Value
End Function
Public Overrides Function IsScopeBlock(node As SyntaxNode) As Boolean
' VB has no equivalent of curly braces.
Return False
End Function
Public Overrides Function IsExecutableBlock(node As SyntaxNode) As Boolean
Return node.IsExecutableBlock()
End Function
Public Overrides Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return node.GetExecutableBlockStatements()
End Function
Public Overrides Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode
Return nodes.FindInnermostCommonExecutableBlock()
End Function
Public Overrides Function IsStatementContainer(node As SyntaxNode) As Boolean
Return IsExecutableBlock(node)
End Function
Public Overrides Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode)
Return GetExecutableBlockStatements(node)
End Function
Public Overrides Function IsConversionExpression(node As SyntaxNode) As Boolean
Return node.Kind = SyntaxKind.CTypeExpression
End Function
Public Overrides Function IsCastExpression(node As SyntaxNode) As Boolean
Return node.Kind = SyntaxKind.DirectCastExpression
End Function
Public Overrides Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode)
Dim cast = DirectCast(node, DirectCastExpressionSyntax)
type = cast.Type
expression = cast.Expression
End Sub
Public Overrides Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location
Throw New NotImplementedException()
End Function
Public Overrides Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken?
If token.Kind() = SyntaxKind.OverridesKeyword Then
Dim parent = token.Parent
Select Case parent.Kind()
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(parent, MethodStatementSyntax)
Return method.Identifier
Case SyntaxKind.PropertyStatement
Dim [property] = DirectCast(parent, PropertyStatementSyntax)
Return [property].Identifier
End Select
End If
Return Nothing
End Function
Public Overrides Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean
' Does not exist in VB.
Return False
End Function
Public Overrides Function IsMemberBindingExpression(node As SyntaxNode) As Boolean
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Overrides Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode)
Return node.GetAttributeLists()
End Function
Public Overrides Function IsUsingAliasDirective(node As SyntaxNode) As Boolean
Dim importStatement = TryCast(node, ImportsStatementSyntax)
If (importStatement IsNot Nothing) Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
Return True
End If
End If
Next
End If
Return False
End Function
Public Overrides Sub GetPartsOfUsingAliasDirective(
node As SyntaxNode,
ByRef globalKeyword As SyntaxToken,
ByRef [alias] As SyntaxToken,
ByRef name As SyntaxNode)
Dim importStatement = DirectCast(node, ImportsStatementSyntax)
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
globalKeyword = Nothing
[alias] = simpleImportsClause.Alias.Identifier
name = simpleImportsClause.Name
Return
End If
End If
Next
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean
Dim xmlElement = TryCast(node, XmlElementSyntax)
If xmlElement IsNot Nothing Then
Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax)
Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName
End If
Return False
End Function
Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode)
Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax)
If documentationCommentTrivia IsNot Nothing Then
Return documentationCommentTrivia.Content
End If
Return Nothing
End Function
Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind)
End Function
Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean
Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement)
End Function
Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer
Dim count As Integer = 0
For i = 0 To nodes.Count - 1
count = count + GetDeclarationCount(nodes(i))
Next
Return count
End Function
Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer
Select Case node.Kind
Case SyntaxKind.FieldDeclaration
Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators)
Case SyntaxKind.LocalDeclarationStatement
Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators)
Case SyntaxKind.VariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Count
Case SyntaxKind.AttributesStatement
Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists)
Case SyntaxKind.AttributeList
Return DirectCast(node, AttributeListSyntax).Attributes.Count
Case SyntaxKind.ImportsStatement
Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count
End Select
Return 1
End Function
Public Overrides Function SupportsNotPattern(options As ParseOptions) As Boolean
Return False
End Function
Public Overrides Function IsIsPatternExpression(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsAnyPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsAndPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsBinaryPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsConstantPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsDeclarationPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsNotPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsOrPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsParenthesizedPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsRecursivePattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsUnaryPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsTypePattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Function IsVarPattern(node As SyntaxNode) As Boolean
Return False
End Function
Public Overrides Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode)
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken)
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode)
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode)
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode)
Throw New NotImplementedException()
End Sub
Public Overrides Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode)
Throw New NotImplementedException()
End Sub
Public Overrides Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode
Throw New NotImplementedException()
End Function
Public Overrides Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken)
Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax)
stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken
contents = interpolatedStringExpressionSyntax.Contents
stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken
End Sub
Public Overrides Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean
Return False
End Function
#Region "IsXXX members"
Public Overrides Function IsAnonymousFunctionExpression(node As SyntaxNode) As Boolean
Return TypeOf node Is LambdaExpressionSyntax
End Function
Public Overrides Function IsBaseNamespaceDeclaration(<NotNullWhen(True)> node As SyntaxNode) As Boolean
Return TypeOf node Is NamespaceBlockSyntax
End Function
Public Overrides Function IsBinaryExpression(node As SyntaxNode) As Boolean
Return TypeOf node Is BinaryExpressionSyntax
End Function
Public Overrides Function IsLiteralExpression(node As SyntaxNode) As Boolean
Return TypeOf node Is LiteralExpressionSyntax
End Function
Public Overrides Function IsMemberAccessExpression(node As SyntaxNode) As Boolean
Return TypeOf node Is MemberAccessExpressionSyntax
End Function
Public Overrides Function IsSimpleName(node As SyntaxNode) As Boolean
Return TypeOf node Is SimpleNameSyntax
End Function
#End Region
#Region "GetPartsOfXXX members"
Public Overrides Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode)
Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax)
left = binaryExpression.Left
operatorToken = binaryExpression.OperatorToken
right = binaryExpression.Right
End Sub
Public Overrides Sub GetPartsOfCompilationUnit(node As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef attributeLists As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode))
Dim compilationUnit = DirectCast(node, CompilationUnitSyntax)
[imports] = compilationUnit.Imports
attributeLists = compilationUnit.Attributes
members = compilationUnit.Members
End Sub
Public Overrides Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode)
Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax)
expression = conditionalAccess.Expression
operatorToken = conditionalAccess.QuestionMarkToken
whenNotNull = conditionalAccess.WhenNotNull
End Sub
Public Overrides Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode)
Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax)
condition = conditionalExpression.Condition
whenTrue = conditionalExpression.WhenTrue
whenFalse = conditionalExpression.WhenFalse
End Sub
Public Overrides Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode)
Dim invocation = DirectCast(node, InvocationExpressionSyntax)
expression = invocation.Expression
argumentList = invocation.ArgumentList
End Sub
Public Overrides Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode)
Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax)
expression = memberAccess.Expression
operatorToken = memberAccess.OperatorToken
name = memberAccess.Name
End Sub
Public Overrides Sub GetPartsOfBaseNamespaceDeclaration(node As SyntaxNode, ByRef name As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode))
Dim namespaceBlock = DirectCast(node, NamespaceBlockSyntax)
name = namespaceBlock.NamespaceStatement.Name
[imports] = Nothing
members = namespaceBlock.Members
End Sub
Public Overrides Sub GetPartsOfObjectCreationExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef argumentList As SyntaxNode, ByRef initializer As SyntaxNode)
Dim objectCreationExpression = DirectCast(node, ObjectCreationExpressionSyntax)
type = objectCreationExpression.Type
argumentList = objectCreationExpression.ArgumentList
initializer = objectCreationExpression.Initializer
End Sub
Public Overrides Sub GetPartsOfParenthesizedExpression(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken)
Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax)
openParen = parenthesizedExpression.OpenParenToken
expression = parenthesizedExpression.Expression
closeParen = parenthesizedExpression.CloseParenToken
End Sub
Public Overrides Sub GetPartsOfPrefixUnaryExpression(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef operand As SyntaxNode)
Dim unaryExpression = DirectCast(node, UnaryExpressionSyntax)
operatorToken = unaryExpression.OperatorToken
operand = unaryExpression.Operand
End Sub
Public Overrides Sub GetPartsOfQualifiedName(node As SyntaxNode, ByRef left As SyntaxNode, ByRef dotToken As SyntaxToken, ByRef right As SyntaxNode)
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
left = qualifiedName.Left
dotToken = qualifiedName.DotToken
right = qualifiedName.Right
End Sub
#End Region
#Region "GetXXXOfYYY members"
Public Overrides Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode
Return DirectCast(node, AwaitExpressionSyntax).Expression
End Function
Public Overrides Function GetExpressionOfThrowExpression(node As SyntaxNode) As SyntaxNode
' ThrowExpression doesn't exist in VB
Throw New NotImplementedException()
End Function
#End Region
End Class
End Namespace
| 1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/Operations/IndentBlockOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting.Rules
{
/// <summary>
/// set indentation level for the given text span. it can be relative, absolute or dependent to other tokens
/// </summary>
internal sealed class IndentBlockOperation
{
internal IndentBlockOperation(SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option)
{
Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.PositionMask));
Contract.ThrowIfTrue(textSpan.Start < 0 || textSpan.Length < 0);
Contract.ThrowIfTrue(startToken.RawKind == 0);
Contract.ThrowIfTrue(endToken.RawKind == 0);
this.BaseToken = default;
this.TextSpan = textSpan;
this.Option = option;
this.StartToken = startToken;
this.EndToken = endToken;
this.IsRelativeIndentation = false;
this.IndentationDeltaOrPosition = indentationDelta;
}
internal IndentBlockOperation(SyntaxToken baseToken, SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option)
{
Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.PositionMask));
Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.RelativePositionMask));
Contract.ThrowIfFalse(baseToken.Span.End <= textSpan.Start);
Contract.ThrowIfTrue(textSpan.Start < 0 || textSpan.Length < 0);
Contract.ThrowIfTrue(startToken.RawKind == 0);
Contract.ThrowIfTrue(endToken.RawKind == 0);
this.BaseToken = baseToken;
this.TextSpan = textSpan;
this.Option = option;
this.StartToken = startToken;
this.EndToken = endToken;
this.IsRelativeIndentation = true;
this.IndentationDeltaOrPosition = indentationDelta;
}
public SyntaxToken BaseToken { get; }
public TextSpan TextSpan { get; }
public IndentBlockOption Option { get; }
public SyntaxToken StartToken { get; }
public SyntaxToken EndToken { get; }
public bool IsRelativeIndentation { get; }
public int IndentationDeltaOrPosition { get; }
#if DEBUG
public override string ToString()
=> $"Indent {TextSpan} from '{StartToken}' to '{EndToken}', by {IndentationDeltaOrPosition}, with base token '{BaseToken}'";
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting.Rules
{
/// <summary>
/// set indentation level for the given text span. it can be relative, absolute or dependent to other tokens
/// </summary>
internal sealed class IndentBlockOperation
{
internal IndentBlockOperation(SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option)
{
Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.PositionMask));
Contract.ThrowIfTrue(textSpan.Start < 0 || textSpan.Length < 0);
Contract.ThrowIfTrue(startToken.RawKind == 0);
Contract.ThrowIfTrue(endToken.RawKind == 0);
this.BaseToken = default;
this.TextSpan = textSpan;
this.Option = option;
this.StartToken = startToken;
this.EndToken = endToken;
this.IsRelativeIndentation = false;
this.IndentationDeltaOrPosition = indentationDelta;
}
internal IndentBlockOperation(SyntaxToken baseToken, SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option)
{
Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.PositionMask));
Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.RelativePositionMask));
Contract.ThrowIfFalse(baseToken.Span.End <= textSpan.Start);
Contract.ThrowIfTrue(textSpan.Start < 0 || textSpan.Length < 0);
Contract.ThrowIfTrue(startToken.RawKind == 0);
Contract.ThrowIfTrue(endToken.RawKind == 0);
this.BaseToken = baseToken;
this.TextSpan = textSpan;
this.Option = option;
this.StartToken = startToken;
this.EndToken = endToken;
this.IsRelativeIndentation = true;
this.IndentationDeltaOrPosition = indentationDelta;
}
public SyntaxToken BaseToken { get; }
public TextSpan TextSpan { get; }
public IndentBlockOption Option { get; }
public SyntaxToken StartToken { get; }
public SyntaxToken EndToken { get; }
public bool IsRelativeIndentation { get; }
public int IndentationDeltaOrPosition { get; }
#if DEBUG
public override string ToString()
=> $"Indent {TextSpan} from '{StartToken}' to '{EndToken}', by {IndentationDeltaOrPosition}, with base token '{BaseToken}'";
#endif
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/Core/Portable/EmbeddedLanguages/DateAndTime/DateAndTimeEmbeddedLanguageFeatures.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Completion;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.EmbeddedLanguages.DateAndTime.LanguageServices;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime
{
internal class DateAndTimeEmbeddedLanguageFeatures : DateAndTimeEmbeddedLanguage, IEmbeddedLanguageFeatures
{
// No highlights currently for date/time literals.
public IDocumentHighlightsService? DocumentHighlightsService { get; }
public CompletionProvider CompletionProvider { get; }
public DateAndTimeEmbeddedLanguageFeatures(
EmbeddedLanguageInfo info) : base(info)
{
CompletionProvider = new DateAndTimeEmbeddedCompletionProvider(this);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Completion;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.EmbeddedLanguages.DateAndTime.LanguageServices;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.DateAndTime
{
internal class DateAndTimeEmbeddedLanguageFeatures : DateAndTimeEmbeddedLanguage, IEmbeddedLanguageFeatures
{
// No highlights currently for date/time literals.
public IDocumentHighlightsService? DocumentHighlightsService { get; }
public CompletionProvider CompletionProvider { get; }
public DateAndTimeEmbeddedLanguageFeatures(
EmbeddedLanguageInfo info) : base(info)
{
CompletionProvider = new DateAndTimeEmbeddedCompletionProvider(this);
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpMiscellaneousReducer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpMiscellaneousReducer : AbstractCSharpReducer
{
private static readonly ObjectPool<IReductionRewriter> s_pool = new(
() => new Rewriter(s_pool));
public CSharpMiscellaneousReducer() : base(s_pool)
{
}
private static bool CanRemoveTypeFromParameter(
ParameterSyntax parameterSyntax,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// We reduce any the parameters that are contained inside ParameterList
if (parameterSyntax.IsParentKind(SyntaxKind.ParameterList) &&
parameterSyntax.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression))
{
if (parameterSyntax.Type != null)
{
var annotation = new SyntaxAnnotation();
var newParameterSyntax = parameterSyntax.WithType(null).WithAdditionalAnnotations(annotation);
var oldLambda = parameterSyntax.FirstAncestorOrSelf<ParenthesizedLambdaExpressionSyntax>();
var newLambda = oldLambda.ReplaceNode(parameterSyntax, newParameterSyntax);
var speculationAnalyzer = new SpeculationAnalyzer(oldLambda, newLambda, semanticModel, cancellationToken);
newParameterSyntax = (ParameterSyntax)speculationAnalyzer.ReplacedExpression.GetAnnotatedNodesAndTokens(annotation).First();
var oldSymbol = semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken);
var newSymbol = speculationAnalyzer.SpeculativeSemanticModel.GetDeclaredSymbol(newParameterSyntax, cancellationToken);
if (oldSymbol != null &&
newSymbol != null &&
Equals(oldSymbol.Type, newSymbol.Type))
{
return !speculationAnalyzer.ReplacementChangesSemantics();
}
}
}
return false;
}
private static readonly Func<ParameterSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParameter = SimplifyParameter;
private static SyntaxNode SimplifyParameter(
ParameterSyntax node,
SemanticModel semanticModel,
OptionSet optionSet,
CancellationToken cancellationToken)
{
if (CanRemoveTypeFromParameter(node, semanticModel, cancellationToken))
{
var newParameterSyntax = node.WithType(null);
newParameterSyntax = SimplificationHelpers.CopyAnnotations(node, newParameterSyntax).WithoutAnnotations(Simplifier.Annotation);
return newParameterSyntax;
}
return node;
}
private static readonly Func<ParenthesizedLambdaExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParenthesizedLambdaExpression = SimplifyParenthesizedLambdaExpression;
private static SyntaxNode SimplifyParenthesizedLambdaExpression(
ParenthesizedLambdaExpressionSyntax parenthesizedLambda,
SemanticModel semanticModel,
OptionSet optionSet,
CancellationToken cancellationToken)
{
if (parenthesizedLambda.ParameterList != null &&
parenthesizedLambda.ParameterList.Parameters.Count == 1)
{
var parameter = parenthesizedLambda.ParameterList.Parameters.First();
if (CanRemoveTypeFromParameter(parameter, semanticModel, cancellationToken))
{
var newParameterSyntax = parameter.WithType(null);
var newSimpleLambda = SyntaxFactory.SimpleLambdaExpression(
parenthesizedLambda.AsyncKeyword,
newParameterSyntax.WithTrailingTrivia(parenthesizedLambda.ParameterList.GetTrailingTrivia()),
parenthesizedLambda.ArrowToken,
parenthesizedLambda.Body);
return SimplificationHelpers.CopyAnnotations(parenthesizedLambda, newSimpleLambda).WithoutAnnotations(Simplifier.Annotation);
}
}
return parenthesizedLambda;
}
private static readonly Func<BlockSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyBlock = SimplifyBlock;
private static SyntaxNode SimplifyBlock(
BlockSyntax node,
SemanticModel semanticModel,
OptionSet optionSet,
CancellationToken cancellationToken)
{
if (node.Statements.Count != 1)
{
return node;
}
if (!CanHaveEmbeddedStatement(node.Parent))
{
return node;
}
switch (optionSet.GetOption(CSharpCodeStyleOptions.PreferBraces).Value)
{
case PreferBracesPreference.Always:
default:
return node;
case PreferBracesPreference.WhenMultiline:
// Braces are optional in several scenarios for 'when_multiline', but are only automatically removed
// in a subset of cases where all of the following are met:
//
// 1. This is an 'if' statement
// 1. The 'if' statement does not have an 'else' clause and is not part of a larger 'if'/'else if'/'else' sequence
// 2. The 'if' statement is not considered multiline
if (!node.Parent.IsKind(SyntaxKind.IfStatement))
{
// Braces are only removed for 'if' statements
return node;
}
if (node.Parent.IsParentKind(SyntaxKind.IfStatement, SyntaxKind.ElseClause))
{
// Braces are not removed from more complicated 'if' sequences
return node;
}
if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Statements[0].GetFirstToken(), node.Statements[0].GetLastToken()))
{
// Braces are not removed when the embedded statement is multiline
return node;
}
if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Parent.GetFirstToken(), node.GetFirstToken().GetPreviousToken()))
{
// Braces are not removed when the part of the 'if' statement preceding the embedded statement
// is multiline.
return node;
}
break;
case PreferBracesPreference.None:
break;
}
return node.Statements[0];
}
private static bool CanHaveEmbeddedStatement(SyntaxNode node)
{
if (node != null)
{
switch (node.Kind())
{
case SyntaxKind.IfStatement:
case SyntaxKind.ElseClause:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.UsingStatement:
case SyntaxKind.LockStatement:
return true;
}
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpMiscellaneousReducer : AbstractCSharpReducer
{
private static readonly ObjectPool<IReductionRewriter> s_pool = new(
() => new Rewriter(s_pool));
public CSharpMiscellaneousReducer() : base(s_pool)
{
}
private static bool CanRemoveTypeFromParameter(
ParameterSyntax parameterSyntax,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// We reduce any the parameters that are contained inside ParameterList
if (parameterSyntax.IsParentKind(SyntaxKind.ParameterList) &&
parameterSyntax.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression))
{
if (parameterSyntax.Type != null)
{
var annotation = new SyntaxAnnotation();
var newParameterSyntax = parameterSyntax.WithType(null).WithAdditionalAnnotations(annotation);
var oldLambda = parameterSyntax.FirstAncestorOrSelf<ParenthesizedLambdaExpressionSyntax>();
var newLambda = oldLambda.ReplaceNode(parameterSyntax, newParameterSyntax);
var speculationAnalyzer = new SpeculationAnalyzer(oldLambda, newLambda, semanticModel, cancellationToken);
newParameterSyntax = (ParameterSyntax)speculationAnalyzer.ReplacedExpression.GetAnnotatedNodesAndTokens(annotation).First();
var oldSymbol = semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken);
var newSymbol = speculationAnalyzer.SpeculativeSemanticModel.GetDeclaredSymbol(newParameterSyntax, cancellationToken);
if (oldSymbol != null &&
newSymbol != null &&
Equals(oldSymbol.Type, newSymbol.Type))
{
return !speculationAnalyzer.ReplacementChangesSemantics();
}
}
}
return false;
}
private static readonly Func<ParameterSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParameter = SimplifyParameter;
private static SyntaxNode SimplifyParameter(
ParameterSyntax node,
SemanticModel semanticModel,
OptionSet optionSet,
CancellationToken cancellationToken)
{
if (CanRemoveTypeFromParameter(node, semanticModel, cancellationToken))
{
var newParameterSyntax = node.WithType(null);
newParameterSyntax = SimplificationHelpers.CopyAnnotations(node, newParameterSyntax).WithoutAnnotations(Simplifier.Annotation);
return newParameterSyntax;
}
return node;
}
private static readonly Func<ParenthesizedLambdaExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParenthesizedLambdaExpression = SimplifyParenthesizedLambdaExpression;
private static SyntaxNode SimplifyParenthesizedLambdaExpression(
ParenthesizedLambdaExpressionSyntax parenthesizedLambda,
SemanticModel semanticModel,
OptionSet optionSet,
CancellationToken cancellationToken)
{
if (parenthesizedLambda.ParameterList != null &&
parenthesizedLambda.ParameterList.Parameters.Count == 1)
{
var parameter = parenthesizedLambda.ParameterList.Parameters.First();
if (CanRemoveTypeFromParameter(parameter, semanticModel, cancellationToken))
{
var newParameterSyntax = parameter.WithType(null);
var newSimpleLambda = SyntaxFactory.SimpleLambdaExpression(
parenthesizedLambda.AsyncKeyword,
newParameterSyntax.WithTrailingTrivia(parenthesizedLambda.ParameterList.GetTrailingTrivia()),
parenthesizedLambda.ArrowToken,
parenthesizedLambda.Body);
return SimplificationHelpers.CopyAnnotations(parenthesizedLambda, newSimpleLambda).WithoutAnnotations(Simplifier.Annotation);
}
}
return parenthesizedLambda;
}
private static readonly Func<BlockSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyBlock = SimplifyBlock;
private static SyntaxNode SimplifyBlock(
BlockSyntax node,
SemanticModel semanticModel,
OptionSet optionSet,
CancellationToken cancellationToken)
{
if (node.Statements.Count != 1)
{
return node;
}
if (!CanHaveEmbeddedStatement(node.Parent))
{
return node;
}
switch (optionSet.GetOption(CSharpCodeStyleOptions.PreferBraces).Value)
{
case PreferBracesPreference.Always:
default:
return node;
case PreferBracesPreference.WhenMultiline:
// Braces are optional in several scenarios for 'when_multiline', but are only automatically removed
// in a subset of cases where all of the following are met:
//
// 1. This is an 'if' statement
// 1. The 'if' statement does not have an 'else' clause and is not part of a larger 'if'/'else if'/'else' sequence
// 2. The 'if' statement is not considered multiline
if (!node.Parent.IsKind(SyntaxKind.IfStatement))
{
// Braces are only removed for 'if' statements
return node;
}
if (node.Parent.IsParentKind(SyntaxKind.IfStatement, SyntaxKind.ElseClause))
{
// Braces are not removed from more complicated 'if' sequences
return node;
}
if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Statements[0].GetFirstToken(), node.Statements[0].GetLastToken()))
{
// Braces are not removed when the embedded statement is multiline
return node;
}
if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Parent.GetFirstToken(), node.GetFirstToken().GetPreviousToken()))
{
// Braces are not removed when the part of the 'if' statement preceding the embedded statement
// is multiline.
return node;
}
break;
case PreferBracesPreference.None:
break;
}
return node.Statements[0];
}
private static bool CanHaveEmbeddedStatement(SyntaxNode node)
{
if (node != null)
{
switch (node.Kind())
{
case SyntaxKind.IfStatement:
case SyntaxKind.ElseClause:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.UsingStatement:
case SyntaxKind.LockStatement:
return true;
}
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/Core/Portable/Workspace/Host/EventListener/ExportEventListenerAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
namespace Microsoft.CodeAnalysis.Host
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportEventListenerAttribute : ExportAttribute
{
public string Service { get; }
public IReadOnlyCollection<string> WorkspaceKinds { get; }
/// <summary>
/// MEF export attribute for <see cref="IEventListener"/>
/// </summary>
/// <param name="service">
/// one of values from <see cref="WellKnownEventListeners"/> indicating which service this event listener is for
/// </param>
/// <param name="workspaceKinds">indicate which workspace kind this event listener is for</param>
public ExportEventListenerAttribute(string service, params string[] workspaceKinds)
: base(typeof(IEventListener))
{
if (workspaceKinds?.Length == 0)
{
throw new ArgumentException(nameof(workspaceKinds));
}
this.Service = service ?? throw new ArgumentException(nameof(service));
this.WorkspaceKinds = workspaceKinds;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
namespace Microsoft.CodeAnalysis.Host
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportEventListenerAttribute : ExportAttribute
{
public string Service { get; }
public IReadOnlyCollection<string> WorkspaceKinds { get; }
/// <summary>
/// MEF export attribute for <see cref="IEventListener"/>
/// </summary>
/// <param name="service">
/// one of values from <see cref="WellKnownEventListeners"/> indicating which service this event listener is for
/// </param>
/// <param name="workspaceKinds">indicate which workspace kind this event listener is for</param>
public ExportEventListenerAttribute(string service, params string[] workspaceKinds)
: base(typeof(IEventListener))
{
if (workspaceKinds?.Length == 0)
{
throw new ArgumentException(nameof(workspaceKinds));
}
this.Service = service ?? throw new ArgumentException(nameof(service));
this.WorkspaceKinds = workspaceKinds;
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/Core/CodeAnalysisTest/Collections/ImmutableArrayExtensionsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class ImmutableArrayExtensionsTests
{
[Fact]
public void CreateFrom()
{
ImmutableArray<int> a;
a = ImmutableArray.Create<int>(2);
Assert.Equal(1, a.Length);
Assert.Equal(2, a[0]);
Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange<int>((IEnumerable<int>)null));
a = ImmutableArray.CreateRange<int>(Enumerable.Range(1, 2));
Assert.Equal(2, a.Length);
Assert.Equal(1, a[0]);
Assert.Equal(2, a[1]);
}
[Fact]
public void ReadOnlyArraysBroken()
{
var b = new ArrayBuilder<String>();
b.Add("hello");
b.Add("world");
Assert.Equal("hello", b[0]);
var a = b.AsImmutable();
Assert.Equal("hello", a[0]);
var e = (IEnumerable<string>)a;
Assert.Equal("hello", e.First());
var aa = e.ToArray();
Assert.Equal("hello", aa[0]);
var first = b.FirstOrDefault((x) => true);
Assert.Equal("hello", first);
ImmutableArray<int> nullOrEmpty = default(ImmutableArray<int>);
Assert.True(nullOrEmpty.IsDefault);
Assert.True(nullOrEmpty.IsDefaultOrEmpty);
Assert.Throws<NullReferenceException>(() => nullOrEmpty.IsEmpty);
nullOrEmpty = ImmutableArray.Create<int>();
Assert.True(nullOrEmpty.IsEmpty);
}
[Fact]
public void InsertAt()
{
var builder = new ArrayBuilder<String>();
builder.Insert(0, "candy");
builder.Insert(0, "apple");
builder.Insert(2, "elephant");
builder.Insert(2, "drum");
builder.Insert(1, "banana");
builder.Insert(0, "$$$");
Assert.Equal("$$$", builder[0]);
Assert.Equal("apple", builder[1]);
Assert.Equal("banana", builder[2]);
Assert.Equal("candy", builder[3]);
Assert.Equal("drum", builder[4]);
Assert.Equal("elephant", builder[5]);
}
[Fact]
public void SetEquals()
{
var nul = default(ImmutableArray<int>);
var empty = ImmutableArray.Create<int>();
var original = new int[] { 1, 2, 3, }.AsImmutableOrNull();
var notEqualSubset = new int[] { 1, 2, }.AsImmutableOrNull();
var notEqualSuperset = new int[] { 1, 2, 3, 4, }.AsImmutableOrNull();
var equalOrder = new int[] { 2, 1, 3, }.AsImmutableOrNull();
var equalElements = new int[] { -1, -2, -3 }.AsImmutableOrNull();
var equalDuplicate = new int[] { 1, 2, 3, 3, -3 }.AsImmutableOrNull();
IEqualityComparer<int> comparer = new AbsoluteValueComparer();
Assert.True(nul.SetEquals(nul, comparer));
Assert.True(empty.SetEquals(empty, comparer));
Assert.True(original.SetEquals(original, comparer));
Assert.True(original.SetEquals(equalOrder, comparer));
Assert.True(original.SetEquals(equalElements, comparer));
Assert.True(original.SetEquals(equalDuplicate, comparer));
Assert.False(nul.SetEquals(empty, comparer));
Assert.False(nul.SetEquals(original, comparer));
Assert.False(empty.SetEquals(nul, comparer));
Assert.False(empty.SetEquals(original, comparer));
Assert.False(original.SetEquals(nul, comparer));
Assert.False(original.SetEquals(empty, comparer));
Assert.False(original.SetEquals(notEqualSubset, comparer));
Assert.False(original.SetEquals(notEqualSuperset, comparer));
//there's a special case for this in the impl, so cover it specially
var singleton1 = ImmutableArray.Create<int>(1);
var singleton2 = ImmutableArray.Create<int>(2);
Assert.True(singleton1.SetEquals(singleton1, comparer));
Assert.False(singleton1.SetEquals(singleton2, comparer));
}
private class AbsoluteValueComparer : IEqualityComparer<int>
{
#region IEqualityComparer<int> Members
bool IEqualityComparer<int>.Equals(int x, int y)
{
return Math.Abs(x) == Math.Abs(y);
}
int IEqualityComparer<int>.GetHashCode(int x)
{
return Math.Abs(x);
}
#endregion
}
[Fact]
public void Single()
{
Assert.Throws<NullReferenceException>(() => default(ImmutableArray<int>).Single());
Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>().Single());
Assert.Equal(1, ImmutableArray.Create<int>(1).Single());
Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>(1, 2).Single());
Func<int, bool> isOdd = x => x % 2 == 1;
// BUG:753260 Should this be ArgumentNullException for consistency?
Assert.Throws<NullReferenceException>(() => default(ImmutableArray<int>).Single(isOdd));
Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>().Single(isOdd));
Assert.Equal(1, ImmutableArray.Create<int>(1, 2).Single(isOdd));
Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>(1, 2, 3).Single(isOdd));
}
[Fact]
public void IndexOf()
{
var roa = new int[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.Equal(1, roa.IndexOf(2));
}
[Fact]
public void CompareToNull()
{
var roaNull = default(ImmutableArray<int>);
Assert.True(roaNull == null);
Assert.False(roaNull != null);
Assert.True(null == roaNull);
Assert.False(null != roaNull);
var copy = roaNull;
Assert.True(copy == roaNull);
Assert.False(copy != roaNull);
var notnull = ImmutableArray.Create<int>();
Assert.False(notnull == null);
Assert.True(notnull != null);
Assert.False(null == notnull);
Assert.True(null != notnull);
}
[Fact]
public void CopyTo()
{
var roa = new int?[] { 1, null, 3 }.AsImmutableOrNull();
var roaCopy = new int?[4];
roa.CopyTo(roaCopy, 1);
Assert.False(roaCopy[0].HasValue);
Assert.Equal(1, roaCopy[1].Value);
Assert.False(roaCopy[2].HasValue);
Assert.Equal(3, roaCopy[3].Value);
}
[Fact]
public void ElementAt()
{
var roa = new int?[] { 1, null, 3 }.AsImmutableOrNull();
Assert.Equal(1, roa.ElementAt(0).Value);
Assert.False(roa.ElementAt(1).HasValue);
Assert.Equal(3, roa.ElementAt(2).Value);
}
[Fact]
public void ElementAtOrDefault()
{
var roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.False(roa.ElementAtOrDefault(-1).HasValue);
Assert.Equal(1, roa.ElementAtOrDefault(0).Value);
Assert.Equal(2, roa.ElementAtOrDefault(1).Value);
Assert.Equal(3, roa.ElementAtOrDefault(2).Value);
Assert.False(roa.ElementAtOrDefault(10).HasValue);
}
[Fact]
public void Last()
{
var roa = new int?[] { }.AsImmutableOrNull();
Assert.Throws<InvalidOperationException>(() => roa.Last());
roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.Throws<InvalidOperationException>(() => roa.Last(i => i < 1));
Assert.Equal(3, roa.Last(i => i > 1));
}
[Fact]
public void LastOrDefault()
{
var roa = new int?[] { }.AsImmutableOrNull();
Assert.False(roa.LastOrDefault().HasValue);
roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.False(roa.LastOrDefault(i => i < 1).HasValue);
Assert.Equal(3, roa.LastOrDefault(i => i > 1));
}
[Fact]
public void SingleOrDefault()
{
var roa = new int?[] { }.AsImmutableOrNull();
Assert.False(roa.SingleOrDefault().HasValue);
roa = new int?[] { 1 }.AsImmutableOrNull();
Assert.Equal(1, roa.SingleOrDefault());
roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.Throws<InvalidOperationException>(() => roa.SingleOrDefault());
roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.Equal(2, roa.SingleOrDefault(i => i == 2));
}
[Fact]
public void Concat()
{
var empty = ImmutableArray.Create<int>();
var a = ImmutableArray.Create<int>(0, 2, 4);
Assert.Equal(empty, empty.Concat(empty));
Assert.Equal(a, a.Concat(empty));
Assert.Equal(a, empty.Concat(a));
Assert.True(a.Concat(a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4)));
}
[Fact]
public void AddRange()
{
var empty = ImmutableArray.Create<int>();
var a = ImmutableArray.Create<int>(0, 2, 4);
Assert.Equal(empty, empty.AddRange(empty));
Assert.Equal(a, a.AddRange(empty));
Assert.Equal(a, empty.AddRange(a));
Assert.True(a.AddRange(a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4)));
Assert.Equal(empty, empty.AddRange((IEnumerable<int>)empty));
Assert.Equal(a, a.AddRange((IEnumerable<int>)empty));
Assert.True(a.SequenceEqual(empty.AddRange((IEnumerable<int>)a)));
Assert.True(a.AddRange((IEnumerable<int>)a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4)));
}
[Fact]
public void InsertRange()
{
var empty = ImmutableArray.Create<int>();
var a = ImmutableArray.Create<int>(0, 2, 4);
Assert.Equal(empty, empty.InsertRange(0, empty));
Assert.Equal(a, a.InsertRange(0, empty));
Assert.Equal(a, a.InsertRange(2, empty));
Assert.True(a.SequenceEqual(empty.InsertRange(0, a)));
Assert.True(a.InsertRange(2, a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 0, 2, 4, 4)));
}
[Fact]
public void ToDictionary()
{
var roa = new string[] { "one:1", "two:2", "three:3" }.AsImmutableOrNull();
// Call extension method directly to resolve the ambiguity with EnumerableExtensions.ToDictionary
var dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First());
Assert.Equal("one:1", dict["one"]);
Assert.Equal("two:2", dict["two"]);
Assert.Equal("three:3", dict["three"]);
Assert.Throws<KeyNotFoundException>(() => dict["One"]);
dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), StringComparer.OrdinalIgnoreCase);
Assert.Equal("one:1", dict["one"]);
Assert.Equal("two:2", dict["Two"]);
Assert.Equal("three:3", dict["THREE"]);
Assert.Throws<KeyNotFoundException>(() => dict[""]);
dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), s => s.Split(':').Last());
Assert.Equal("1", dict["one"]);
Assert.Equal("2", dict["two"]);
Assert.Equal("3", dict["three"]);
Assert.Throws<KeyNotFoundException>(() => dict["THREE"]);
dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), s => s.Split(':').Last(), StringComparer.OrdinalIgnoreCase);
Assert.Equal("1", dict["onE"]);
Assert.Equal("2", dict["Two"]);
Assert.Equal("3", dict["three"]);
Assert.Throws<KeyNotFoundException>(() => dict["four"]);
}
[Fact]
public void SequenceEqual()
{
var a = ImmutableArray.Create<string>("A", "B", "C");
var b = ImmutableArray.Create<string>("A", "b", "c");
var c = ImmutableArray.Create<string>("A", "b");
Assert.False(a.SequenceEqual(b));
Assert.True(a.SequenceEqual(b, StringComparer.OrdinalIgnoreCase));
Assert.False(a.SequenceEqual(c));
Assert.False(a.SequenceEqual(c, StringComparer.OrdinalIgnoreCase));
Assert.False(c.SequenceEqual(a));
var r = ImmutableArray.Create<int>(1, 2, 3);
Assert.True(r.SequenceEqual(Enumerable.Range(1, 3)));
Assert.False(r.SequenceEqual(Enumerable.Range(1, 2)));
Assert.False(r.SequenceEqual(Enumerable.Range(1, 4)));
var s = ImmutableArray.Create<int>(10, 20, 30);
Assert.True(r.SequenceEqual(s, (x, y) => 10 * x == y));
}
[Fact]
public void SelectAsArray()
{
var empty = ImmutableArray.Create<object>();
Assert.True(empty.SequenceEqual(empty.SelectAsArray(item => item)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, arg) => item, 1)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, arg) => arg, 2)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => item, 1)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => arg, 2)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => index, 3)));
var a = ImmutableArray.Create<int>(3, 2, 1, 0);
var b = ImmutableArray.Create<int>(0, 1, 2, 3);
var c = ImmutableArray.Create<int>(2, 2, 2, 2);
Assert.True(a.SequenceEqual(a.SelectAsArray(item => item)));
Assert.True(a.SequenceEqual(a.SelectAsArray((item, arg) => item, 1)));
Assert.True(c.SequenceEqual(a.SelectAsArray((item, arg) => arg, 2)));
Assert.True(a.SequenceEqual(a.SelectAsArray((item, index, arg) => item, 1)));
Assert.True(c.SequenceEqual(a.SelectAsArray((item, index, arg) => arg, 2)));
Assert.True(b.SequenceEqual(a.SelectAsArray((item, index, arg) => index, 3)));
AssertEx.Equal(new[] { 10 }, ImmutableArray.Create(1).SelectAsArray(i => 10 * i));
AssertEx.Equal(new[] { 10, 20 }, ImmutableArray.Create(1, 2).SelectAsArray(i => 10 * i));
AssertEx.Equal(new[] { 10, 20, 30 }, ImmutableArray.Create(1, 2, 3).SelectAsArray(i => 10 * i));
AssertEx.Equal(new[] { 10, 20, 30, 40 }, ImmutableArray.Create(1, 2, 3, 4).SelectAsArray(i => 10 * i));
AssertEx.Equal(new[] { 10, 20, 30, 40, 50 }, ImmutableArray.Create(1, 2, 3, 4, 5).SelectAsArray(i => 10 * i));
}
[Fact]
public void SelectAsArrayWithPredicate()
{
Assert.Empty(ImmutableArray<object>.Empty.SelectAsArray<object, int>(item => throw null, item => throw null));
var array = ImmutableArray.Create(1, 2, 3, 4, 5);
AssertEx.Equal(new[] { 2, 3, 4, 5, 6 }, array.SelectAsArray(item => true, item => item + 1));
AssertEx.Equal(new[] { 3, 5 }, array.SelectAsArray(item => item % 2 == 0, item => item + 1));
Assert.Empty(array.SelectAsArray<int, int>(item => item < 0, item => throw null));
}
[Fact]
public void ZipAsArray()
{
var empty = ImmutableArray.Create<object>();
Assert.True(empty.SequenceEqual(empty.ZipAsArray(empty, (item1, item2) => item1)));
var single1 = ImmutableArray.Create(1);
var single2 = ImmutableArray.Create(10);
var single3 = ImmutableArray.Create(11);
Assert.True(single3.SequenceEqual(single1.ZipAsArray(single2, (item1, item2) => item1 + item2)));
var pair1 = ImmutableArray.Create(1, 2);
var pair2 = ImmutableArray.Create(10, 11);
var pair3 = ImmutableArray.Create(11, 13);
Assert.True(pair3.SequenceEqual(pair1.ZipAsArray(pair2, (item1, item2) => item1 + item2)));
var triple1 = ImmutableArray.Create(1, 2, 3);
var triple2 = ImmutableArray.Create(10, 11, 12);
var triple3 = ImmutableArray.Create(11, 13, 15);
Assert.True(triple3.SequenceEqual(triple1.ZipAsArray(triple2, (item1, item2) => item1 + item2)));
var quad1 = ImmutableArray.Create(1, 2, 3, 4);
var quad2 = ImmutableArray.Create(10, 11, 12, 13);
var quad3 = ImmutableArray.Create(11, 13, 15, 17);
Assert.True(quad3.SequenceEqual(quad1.ZipAsArray(quad2, (item1, item2) => item1 + item2)));
var quin1 = ImmutableArray.Create(1, 2, 3, 4, 5);
var quin2 = ImmutableArray.Create(10, 11, 12, 13, 14);
var quin3 = ImmutableArray.Create(11, 13, 15, 17, 19);
Assert.True(quin3.SequenceEqual(quin1.ZipAsArray(quin2, (item1, item2) => item1 + item2)));
}
[Fact]
public void ZipAsArrayWithIndex()
{
var empty = ImmutableArray.Create<object>();
Assert.True(empty.SequenceEqual(empty.ZipAsArray(empty, (item1, item2) => item1)));
var single1 = ImmutableArray.Create(1);
var single2 = ImmutableArray.Create(10);
var single3 = ImmutableArray.Create(13);
Assert.True(single3.SequenceEqual(single1.ZipAsArray(single2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
var pair1 = ImmutableArray.Create(1, 2);
var pair2 = ImmutableArray.Create(10, 11);
var pair3 = ImmutableArray.Create(13, 16);
Assert.True(pair3.SequenceEqual(pair1.ZipAsArray(pair2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
var triple1 = ImmutableArray.Create(1, 2, 3);
var triple2 = ImmutableArray.Create(10, 11, 12);
var triple3 = ImmutableArray.Create(13, 16, 19);
Assert.True(triple3.SequenceEqual(triple1.ZipAsArray(triple2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
var quad1 = ImmutableArray.Create(1, 2, 3, 4);
var quad2 = ImmutableArray.Create(10, 11, 12, 13);
var quad3 = ImmutableArray.Create(13, 16, 19, 22);
Assert.True(quad3.SequenceEqual(quad1.ZipAsArray(quad2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
var quin1 = ImmutableArray.Create(1, 2, 3, 4, 5);
var quin2 = ImmutableArray.Create(10, 11, 12, 13, 14);
var quin3 = ImmutableArray.Create(13, 16, 19, 22, 25);
Assert.True(quin3.SequenceEqual(quin1.ZipAsArray(quin2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
}
[Fact]
public void WhereAsArray()
{
var empty = ImmutableArray.Create<object>();
// All.
Assert.Equal(empty, empty.WhereAsArray(o => true));
// None.
Assert.Equal(empty, empty.WhereAsArray(o => false));
var a = ImmutableArray.Create<int>(0, 1, 2, 3, 4, 5);
// All.
Assert.Equal(a, a.WhereAsArray(i => true));
// None.
Assert.True(a.WhereAsArray(i => false).SequenceEqual(ImmutableArray.Create<int>()));
// All but the first.
Assert.True(a.WhereAsArray(i => i > 0).SequenceEqual(ImmutableArray.Create<int>(1, 2, 3, 4, 5)));
// All but the last.
Assert.True(a.WhereAsArray(i => i < 5).SequenceEqual(ImmutableArray.Create<int>(0, 1, 2, 3, 4)));
// First only.
Assert.True(a.WhereAsArray(i => i == 0).SequenceEqual(ImmutableArray.Create<int>(0)));
// Last only.
Assert.True(a.WhereAsArray(i => i == 5).SequenceEqual(ImmutableArray.Create<int>(5)));
// First half.
Assert.True(a.WhereAsArray(i => i < 3).SequenceEqual(ImmutableArray.Create<int>(0, 1, 2)));
// Second half.
Assert.True(a.WhereAsArray(i => i > 2).SequenceEqual(ImmutableArray.Create<int>(3, 4, 5)));
// Even.
Assert.True(a.WhereAsArray(i => i % 2 == 0).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4)));
// Odd.
Assert.True(a.WhereAsArray(i => i % 2 == 1).SequenceEqual(ImmutableArray.Create<int>(1, 3, 5)));
}
[Fact]
public void WhereAsArray_WithArg()
{
var x = new C();
Assert.Same(x, ImmutableArray.Create<object>(x).WhereAsArray((o, arg) => o == arg, x)[0]);
var a = ImmutableArray.Create(0, 1, 2, 3, 4, 5);
AssertEx.Equal(new[] { 3, 4, 5 }, a.WhereAsArray((i, j) => i > j, 2));
}
private class C
{
}
private class D : C
{
}
[Fact]
public void Casting()
{
var arrayOfD = new D[] { new D() }.AsImmutableOrNull();
var arrayOfC = arrayOfD.Cast<D, C>();
var arrayOfD2 = arrayOfC.As<D>();
// the underlying arrays are the same:
//Assert.True(arrayOfD.Equals(arrayOfC));
Assert.True(arrayOfD2.Equals(arrayOfD));
// Trying to cast from base to derived. "As" should return null (default)
Assert.True(new C[] { new C() }.AsImmutableOrNull().As<D>().IsDefault);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class ImmutableArrayExtensionsTests
{
[Fact]
public void CreateFrom()
{
ImmutableArray<int> a;
a = ImmutableArray.Create<int>(2);
Assert.Equal(1, a.Length);
Assert.Equal(2, a[0]);
Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange<int>((IEnumerable<int>)null));
a = ImmutableArray.CreateRange<int>(Enumerable.Range(1, 2));
Assert.Equal(2, a.Length);
Assert.Equal(1, a[0]);
Assert.Equal(2, a[1]);
}
[Fact]
public void ReadOnlyArraysBroken()
{
var b = new ArrayBuilder<String>();
b.Add("hello");
b.Add("world");
Assert.Equal("hello", b[0]);
var a = b.AsImmutable();
Assert.Equal("hello", a[0]);
var e = (IEnumerable<string>)a;
Assert.Equal("hello", e.First());
var aa = e.ToArray();
Assert.Equal("hello", aa[0]);
var first = b.FirstOrDefault((x) => true);
Assert.Equal("hello", first);
ImmutableArray<int> nullOrEmpty = default(ImmutableArray<int>);
Assert.True(nullOrEmpty.IsDefault);
Assert.True(nullOrEmpty.IsDefaultOrEmpty);
Assert.Throws<NullReferenceException>(() => nullOrEmpty.IsEmpty);
nullOrEmpty = ImmutableArray.Create<int>();
Assert.True(nullOrEmpty.IsEmpty);
}
[Fact]
public void InsertAt()
{
var builder = new ArrayBuilder<String>();
builder.Insert(0, "candy");
builder.Insert(0, "apple");
builder.Insert(2, "elephant");
builder.Insert(2, "drum");
builder.Insert(1, "banana");
builder.Insert(0, "$$$");
Assert.Equal("$$$", builder[0]);
Assert.Equal("apple", builder[1]);
Assert.Equal("banana", builder[2]);
Assert.Equal("candy", builder[3]);
Assert.Equal("drum", builder[4]);
Assert.Equal("elephant", builder[5]);
}
[Fact]
public void SetEquals()
{
var nul = default(ImmutableArray<int>);
var empty = ImmutableArray.Create<int>();
var original = new int[] { 1, 2, 3, }.AsImmutableOrNull();
var notEqualSubset = new int[] { 1, 2, }.AsImmutableOrNull();
var notEqualSuperset = new int[] { 1, 2, 3, 4, }.AsImmutableOrNull();
var equalOrder = new int[] { 2, 1, 3, }.AsImmutableOrNull();
var equalElements = new int[] { -1, -2, -3 }.AsImmutableOrNull();
var equalDuplicate = new int[] { 1, 2, 3, 3, -3 }.AsImmutableOrNull();
IEqualityComparer<int> comparer = new AbsoluteValueComparer();
Assert.True(nul.SetEquals(nul, comparer));
Assert.True(empty.SetEquals(empty, comparer));
Assert.True(original.SetEquals(original, comparer));
Assert.True(original.SetEquals(equalOrder, comparer));
Assert.True(original.SetEquals(equalElements, comparer));
Assert.True(original.SetEquals(equalDuplicate, comparer));
Assert.False(nul.SetEquals(empty, comparer));
Assert.False(nul.SetEquals(original, comparer));
Assert.False(empty.SetEquals(nul, comparer));
Assert.False(empty.SetEquals(original, comparer));
Assert.False(original.SetEquals(nul, comparer));
Assert.False(original.SetEquals(empty, comparer));
Assert.False(original.SetEquals(notEqualSubset, comparer));
Assert.False(original.SetEquals(notEqualSuperset, comparer));
//there's a special case for this in the impl, so cover it specially
var singleton1 = ImmutableArray.Create<int>(1);
var singleton2 = ImmutableArray.Create<int>(2);
Assert.True(singleton1.SetEquals(singleton1, comparer));
Assert.False(singleton1.SetEquals(singleton2, comparer));
}
private class AbsoluteValueComparer : IEqualityComparer<int>
{
#region IEqualityComparer<int> Members
bool IEqualityComparer<int>.Equals(int x, int y)
{
return Math.Abs(x) == Math.Abs(y);
}
int IEqualityComparer<int>.GetHashCode(int x)
{
return Math.Abs(x);
}
#endregion
}
[Fact]
public void Single()
{
Assert.Throws<NullReferenceException>(() => default(ImmutableArray<int>).Single());
Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>().Single());
Assert.Equal(1, ImmutableArray.Create<int>(1).Single());
Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>(1, 2).Single());
Func<int, bool> isOdd = x => x % 2 == 1;
// BUG:753260 Should this be ArgumentNullException for consistency?
Assert.Throws<NullReferenceException>(() => default(ImmutableArray<int>).Single(isOdd));
Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>().Single(isOdd));
Assert.Equal(1, ImmutableArray.Create<int>(1, 2).Single(isOdd));
Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>(1, 2, 3).Single(isOdd));
}
[Fact]
public void IndexOf()
{
var roa = new int[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.Equal(1, roa.IndexOf(2));
}
[Fact]
public void CompareToNull()
{
var roaNull = default(ImmutableArray<int>);
Assert.True(roaNull == null);
Assert.False(roaNull != null);
Assert.True(null == roaNull);
Assert.False(null != roaNull);
var copy = roaNull;
Assert.True(copy == roaNull);
Assert.False(copy != roaNull);
var notnull = ImmutableArray.Create<int>();
Assert.False(notnull == null);
Assert.True(notnull != null);
Assert.False(null == notnull);
Assert.True(null != notnull);
}
[Fact]
public void CopyTo()
{
var roa = new int?[] { 1, null, 3 }.AsImmutableOrNull();
var roaCopy = new int?[4];
roa.CopyTo(roaCopy, 1);
Assert.False(roaCopy[0].HasValue);
Assert.Equal(1, roaCopy[1].Value);
Assert.False(roaCopy[2].HasValue);
Assert.Equal(3, roaCopy[3].Value);
}
[Fact]
public void ElementAt()
{
var roa = new int?[] { 1, null, 3 }.AsImmutableOrNull();
Assert.Equal(1, roa.ElementAt(0).Value);
Assert.False(roa.ElementAt(1).HasValue);
Assert.Equal(3, roa.ElementAt(2).Value);
}
[Fact]
public void ElementAtOrDefault()
{
var roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.False(roa.ElementAtOrDefault(-1).HasValue);
Assert.Equal(1, roa.ElementAtOrDefault(0).Value);
Assert.Equal(2, roa.ElementAtOrDefault(1).Value);
Assert.Equal(3, roa.ElementAtOrDefault(2).Value);
Assert.False(roa.ElementAtOrDefault(10).HasValue);
}
[Fact]
public void Last()
{
var roa = new int?[] { }.AsImmutableOrNull();
Assert.Throws<InvalidOperationException>(() => roa.Last());
roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.Throws<InvalidOperationException>(() => roa.Last(i => i < 1));
Assert.Equal(3, roa.Last(i => i > 1));
}
[Fact]
public void LastOrDefault()
{
var roa = new int?[] { }.AsImmutableOrNull();
Assert.False(roa.LastOrDefault().HasValue);
roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.False(roa.LastOrDefault(i => i < 1).HasValue);
Assert.Equal(3, roa.LastOrDefault(i => i > 1));
}
[Fact]
public void SingleOrDefault()
{
var roa = new int?[] { }.AsImmutableOrNull();
Assert.False(roa.SingleOrDefault().HasValue);
roa = new int?[] { 1 }.AsImmutableOrNull();
Assert.Equal(1, roa.SingleOrDefault());
roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.Throws<InvalidOperationException>(() => roa.SingleOrDefault());
roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull();
Assert.Equal(2, roa.SingleOrDefault(i => i == 2));
}
[Fact]
public void Concat()
{
var empty = ImmutableArray.Create<int>();
var a = ImmutableArray.Create<int>(0, 2, 4);
Assert.Equal(empty, empty.Concat(empty));
Assert.Equal(a, a.Concat(empty));
Assert.Equal(a, empty.Concat(a));
Assert.True(a.Concat(a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4)));
}
[Fact]
public void AddRange()
{
var empty = ImmutableArray.Create<int>();
var a = ImmutableArray.Create<int>(0, 2, 4);
Assert.Equal(empty, empty.AddRange(empty));
Assert.Equal(a, a.AddRange(empty));
Assert.Equal(a, empty.AddRange(a));
Assert.True(a.AddRange(a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4)));
Assert.Equal(empty, empty.AddRange((IEnumerable<int>)empty));
Assert.Equal(a, a.AddRange((IEnumerable<int>)empty));
Assert.True(a.SequenceEqual(empty.AddRange((IEnumerable<int>)a)));
Assert.True(a.AddRange((IEnumerable<int>)a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4)));
}
[Fact]
public void InsertRange()
{
var empty = ImmutableArray.Create<int>();
var a = ImmutableArray.Create<int>(0, 2, 4);
Assert.Equal(empty, empty.InsertRange(0, empty));
Assert.Equal(a, a.InsertRange(0, empty));
Assert.Equal(a, a.InsertRange(2, empty));
Assert.True(a.SequenceEqual(empty.InsertRange(0, a)));
Assert.True(a.InsertRange(2, a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 0, 2, 4, 4)));
}
[Fact]
public void ToDictionary()
{
var roa = new string[] { "one:1", "two:2", "three:3" }.AsImmutableOrNull();
// Call extension method directly to resolve the ambiguity with EnumerableExtensions.ToDictionary
var dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First());
Assert.Equal("one:1", dict["one"]);
Assert.Equal("two:2", dict["two"]);
Assert.Equal("three:3", dict["three"]);
Assert.Throws<KeyNotFoundException>(() => dict["One"]);
dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), StringComparer.OrdinalIgnoreCase);
Assert.Equal("one:1", dict["one"]);
Assert.Equal("two:2", dict["Two"]);
Assert.Equal("three:3", dict["THREE"]);
Assert.Throws<KeyNotFoundException>(() => dict[""]);
dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), s => s.Split(':').Last());
Assert.Equal("1", dict["one"]);
Assert.Equal("2", dict["two"]);
Assert.Equal("3", dict["three"]);
Assert.Throws<KeyNotFoundException>(() => dict["THREE"]);
dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), s => s.Split(':').Last(), StringComparer.OrdinalIgnoreCase);
Assert.Equal("1", dict["onE"]);
Assert.Equal("2", dict["Two"]);
Assert.Equal("3", dict["three"]);
Assert.Throws<KeyNotFoundException>(() => dict["four"]);
}
[Fact]
public void SequenceEqual()
{
var a = ImmutableArray.Create<string>("A", "B", "C");
var b = ImmutableArray.Create<string>("A", "b", "c");
var c = ImmutableArray.Create<string>("A", "b");
Assert.False(a.SequenceEqual(b));
Assert.True(a.SequenceEqual(b, StringComparer.OrdinalIgnoreCase));
Assert.False(a.SequenceEqual(c));
Assert.False(a.SequenceEqual(c, StringComparer.OrdinalIgnoreCase));
Assert.False(c.SequenceEqual(a));
var r = ImmutableArray.Create<int>(1, 2, 3);
Assert.True(r.SequenceEqual(Enumerable.Range(1, 3)));
Assert.False(r.SequenceEqual(Enumerable.Range(1, 2)));
Assert.False(r.SequenceEqual(Enumerable.Range(1, 4)));
var s = ImmutableArray.Create<int>(10, 20, 30);
Assert.True(r.SequenceEqual(s, (x, y) => 10 * x == y));
}
[Fact]
public void SelectAsArray()
{
var empty = ImmutableArray.Create<object>();
Assert.True(empty.SequenceEqual(empty.SelectAsArray(item => item)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, arg) => item, 1)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, arg) => arg, 2)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => item, 1)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => arg, 2)));
Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => index, 3)));
var a = ImmutableArray.Create<int>(3, 2, 1, 0);
var b = ImmutableArray.Create<int>(0, 1, 2, 3);
var c = ImmutableArray.Create<int>(2, 2, 2, 2);
Assert.True(a.SequenceEqual(a.SelectAsArray(item => item)));
Assert.True(a.SequenceEqual(a.SelectAsArray((item, arg) => item, 1)));
Assert.True(c.SequenceEqual(a.SelectAsArray((item, arg) => arg, 2)));
Assert.True(a.SequenceEqual(a.SelectAsArray((item, index, arg) => item, 1)));
Assert.True(c.SequenceEqual(a.SelectAsArray((item, index, arg) => arg, 2)));
Assert.True(b.SequenceEqual(a.SelectAsArray((item, index, arg) => index, 3)));
AssertEx.Equal(new[] { 10 }, ImmutableArray.Create(1).SelectAsArray(i => 10 * i));
AssertEx.Equal(new[] { 10, 20 }, ImmutableArray.Create(1, 2).SelectAsArray(i => 10 * i));
AssertEx.Equal(new[] { 10, 20, 30 }, ImmutableArray.Create(1, 2, 3).SelectAsArray(i => 10 * i));
AssertEx.Equal(new[] { 10, 20, 30, 40 }, ImmutableArray.Create(1, 2, 3, 4).SelectAsArray(i => 10 * i));
AssertEx.Equal(new[] { 10, 20, 30, 40, 50 }, ImmutableArray.Create(1, 2, 3, 4, 5).SelectAsArray(i => 10 * i));
}
[Fact]
public void SelectAsArrayWithPredicate()
{
Assert.Empty(ImmutableArray<object>.Empty.SelectAsArray<object, int>(item => throw null, item => throw null));
var array = ImmutableArray.Create(1, 2, 3, 4, 5);
AssertEx.Equal(new[] { 2, 3, 4, 5, 6 }, array.SelectAsArray(item => true, item => item + 1));
AssertEx.Equal(new[] { 3, 5 }, array.SelectAsArray(item => item % 2 == 0, item => item + 1));
Assert.Empty(array.SelectAsArray<int, int>(item => item < 0, item => throw null));
}
[Fact]
public void ZipAsArray()
{
var empty = ImmutableArray.Create<object>();
Assert.True(empty.SequenceEqual(empty.ZipAsArray(empty, (item1, item2) => item1)));
var single1 = ImmutableArray.Create(1);
var single2 = ImmutableArray.Create(10);
var single3 = ImmutableArray.Create(11);
Assert.True(single3.SequenceEqual(single1.ZipAsArray(single2, (item1, item2) => item1 + item2)));
var pair1 = ImmutableArray.Create(1, 2);
var pair2 = ImmutableArray.Create(10, 11);
var pair3 = ImmutableArray.Create(11, 13);
Assert.True(pair3.SequenceEqual(pair1.ZipAsArray(pair2, (item1, item2) => item1 + item2)));
var triple1 = ImmutableArray.Create(1, 2, 3);
var triple2 = ImmutableArray.Create(10, 11, 12);
var triple3 = ImmutableArray.Create(11, 13, 15);
Assert.True(triple3.SequenceEqual(triple1.ZipAsArray(triple2, (item1, item2) => item1 + item2)));
var quad1 = ImmutableArray.Create(1, 2, 3, 4);
var quad2 = ImmutableArray.Create(10, 11, 12, 13);
var quad3 = ImmutableArray.Create(11, 13, 15, 17);
Assert.True(quad3.SequenceEqual(quad1.ZipAsArray(quad2, (item1, item2) => item1 + item2)));
var quin1 = ImmutableArray.Create(1, 2, 3, 4, 5);
var quin2 = ImmutableArray.Create(10, 11, 12, 13, 14);
var quin3 = ImmutableArray.Create(11, 13, 15, 17, 19);
Assert.True(quin3.SequenceEqual(quin1.ZipAsArray(quin2, (item1, item2) => item1 + item2)));
}
[Fact]
public void ZipAsArrayWithIndex()
{
var empty = ImmutableArray.Create<object>();
Assert.True(empty.SequenceEqual(empty.ZipAsArray(empty, (item1, item2) => item1)));
var single1 = ImmutableArray.Create(1);
var single2 = ImmutableArray.Create(10);
var single3 = ImmutableArray.Create(13);
Assert.True(single3.SequenceEqual(single1.ZipAsArray(single2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
var pair1 = ImmutableArray.Create(1, 2);
var pair2 = ImmutableArray.Create(10, 11);
var pair3 = ImmutableArray.Create(13, 16);
Assert.True(pair3.SequenceEqual(pair1.ZipAsArray(pair2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
var triple1 = ImmutableArray.Create(1, 2, 3);
var triple2 = ImmutableArray.Create(10, 11, 12);
var triple3 = ImmutableArray.Create(13, 16, 19);
Assert.True(triple3.SequenceEqual(triple1.ZipAsArray(triple2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
var quad1 = ImmutableArray.Create(1, 2, 3, 4);
var quad2 = ImmutableArray.Create(10, 11, 12, 13);
var quad3 = ImmutableArray.Create(13, 16, 19, 22);
Assert.True(quad3.SequenceEqual(quad1.ZipAsArray(quad2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
var quin1 = ImmutableArray.Create(1, 2, 3, 4, 5);
var quin2 = ImmutableArray.Create(10, 11, 12, 13, 14);
var quin3 = ImmutableArray.Create(13, 16, 19, 22, 25);
Assert.True(quin3.SequenceEqual(quin1.ZipAsArray(quin2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg)));
}
[Fact]
public void WhereAsArray()
{
var empty = ImmutableArray.Create<object>();
// All.
Assert.Equal(empty, empty.WhereAsArray(o => true));
// None.
Assert.Equal(empty, empty.WhereAsArray(o => false));
var a = ImmutableArray.Create<int>(0, 1, 2, 3, 4, 5);
// All.
Assert.Equal(a, a.WhereAsArray(i => true));
// None.
Assert.True(a.WhereAsArray(i => false).SequenceEqual(ImmutableArray.Create<int>()));
// All but the first.
Assert.True(a.WhereAsArray(i => i > 0).SequenceEqual(ImmutableArray.Create<int>(1, 2, 3, 4, 5)));
// All but the last.
Assert.True(a.WhereAsArray(i => i < 5).SequenceEqual(ImmutableArray.Create<int>(0, 1, 2, 3, 4)));
// First only.
Assert.True(a.WhereAsArray(i => i == 0).SequenceEqual(ImmutableArray.Create<int>(0)));
// Last only.
Assert.True(a.WhereAsArray(i => i == 5).SequenceEqual(ImmutableArray.Create<int>(5)));
// First half.
Assert.True(a.WhereAsArray(i => i < 3).SequenceEqual(ImmutableArray.Create<int>(0, 1, 2)));
// Second half.
Assert.True(a.WhereAsArray(i => i > 2).SequenceEqual(ImmutableArray.Create<int>(3, 4, 5)));
// Even.
Assert.True(a.WhereAsArray(i => i % 2 == 0).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4)));
// Odd.
Assert.True(a.WhereAsArray(i => i % 2 == 1).SequenceEqual(ImmutableArray.Create<int>(1, 3, 5)));
}
[Fact]
public void WhereAsArray_WithArg()
{
var x = new C();
Assert.Same(x, ImmutableArray.Create<object>(x).WhereAsArray((o, arg) => o == arg, x)[0]);
var a = ImmutableArray.Create(0, 1, 2, 3, 4, 5);
AssertEx.Equal(new[] { 3, 4, 5 }, a.WhereAsArray((i, j) => i > j, 2));
}
private class C
{
}
private class D : C
{
}
[Fact]
public void Casting()
{
var arrayOfD = new D[] { new D() }.AsImmutableOrNull();
var arrayOfC = arrayOfD.Cast<D, C>();
var arrayOfD2 = arrayOfC.As<D>();
// the underlying arrays are the same:
//Assert.True(arrayOfD.Equals(arrayOfC));
Assert.True(arrayOfD2.Equals(arrayOfD));
// Trying to cast from base to derived. "As" should return null (default)
Assert.True(new C[] { new C() }.AsImmutableOrNull().As<D>().IsDefault);
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/CSharp/Portable/CodeGeneration/StatementGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class StatementGenerator
{
internal static SyntaxList<StatementSyntax> GenerateStatements(IEnumerable<SyntaxNode> statements)
=> statements.OfType<StatementSyntax>().ToSyntaxList();
internal static BlockSyntax GenerateBlock(IMethodSymbol method)
{
return SyntaxFactory.Block(
StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(method)));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class StatementGenerator
{
internal static SyntaxList<StatementSyntax> GenerateStatements(IEnumerable<SyntaxNode> statements)
=> statements.OfType<StatementSyntax>().ToSyntaxList();
internal static BlockSyntax GenerateBlock(IMethodSymbol method)
{
return SyntaxFactory.Block(
StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(method)));
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_FlowAnalysis.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Partial Public Class FlowAnalysisTests
<Fact>
Public Sub Query1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As QueryAble
Dim q1 As Object = From s In q Where 2 > s
Dim x1, x2, x3, x4 As Object
Dim qq As New QueryAble()
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'q' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q1 As Object = From s In q Where 2 > s
~
BC42104: Variable 'x1' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
~~
BC42104: Variable 'x2' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
~~
BC42104: Variable 'x3' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
~~
BC42104: Variable 'x4' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
~~
</expected>)
End Sub
<Fact>
Public Sub Query2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In q
Where [|s1 > 0|]
Where 10 > s1 + y
Where DirectCast(Function()
System.Console.WriteLine(s1)
Return True
End Function, Func(Of Boolean)).Invoke()
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact>
Public Sub Query3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In [|q|]
Where s1 > 0
Where 10 > s1 + y
Where DirectCast(Function()
System.Console.WriteLine(s1)
Return True
End Function, Func(Of Boolean)).Invoke()
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact>
Public Sub Query7()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = [|From s1 In q
Where s1 > 0
Where 10 > s1 + y
Where DirectCast(Function()
System.Console.WriteLine(s1)
Return True
End Function, Func(Of Boolean)).Invoke()|]
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Query4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In q
Where s1 > 0
Where 10 > s1 + y
Where [|DirectCast(Function()
Dim z As Integer = 0
y=s1
System.Console.WriteLine(s1+z)
Return True
End Function, Func(Of Boolean))|].Invoke()
System.Console.WriteLine(y)
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Query5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In q
Where s1 > 0
Where 10 > [|s1 + y|]
Where DirectCast(Function()
Dim z As Integer = 0
y=s1
System.Console.WriteLine(s1+z)
Return True
End Function, Func(Of Boolean)).Invoke()
System.Console.WriteLine(y)
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, y, s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select [|s1|]
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Dim flowsIn = dataFlowAnalysisResults.DataFlowsIn(0)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Same(flowsIn, dataFlowAnalysisResults.ReadInside(0))
Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Dim ss = dataFlowAnalysisResults.WrittenOutside.Where(Function(s) s.Name.Equals("s1", StringComparison.OrdinalIgnoreCase))
Assert.Equal(ss(0).Name, ss(1).Name)
Assert.NotEqual(ss(0), ss(1))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = [|From s1 In q
Select s1
Where 10 > s1|]
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal("s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.NotSame(dataFlowAnalysisResults.VariablesDeclared(0), dataFlowAnalysisResults.VariablesDeclared(1))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select s1 = [|s1|]
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.NotSame(dataFlowAnalysisResults.ReadInside(0), GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)(1))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select s2 = [|s1|]
Where 10 > s2
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select [|s1 + 1|]
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In [|q|]
Select s1 + 1
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select7()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In [|q|]
Select 1
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select8()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select s2 = [|s1|]
Where 10 > s2
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select9()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select s2 = [|s1|]
Where 10 > s2
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub ImplicitSelect1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Long In [|q|] Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub ImplicitSelect2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Long In [|q|] Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub ImplicitSelect3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Long In [|q|] Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact()>
Public Sub ImplicitSelect4()
Assert.Throws(Of System.ArgumentException)(
Sub()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s [|As Long|] In q Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
End Sub)
#If False Then
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured))
#End If
End Sub
<Fact>
Public Sub ImplicitSelect5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = [|From s As Long In q Where s > 1|]
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact()>
Public Sub ImplicitSelect6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As [|Long|] In q Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
#If True Then
Assert.False(dataFlowAnalysisResults.Succeeded)
#Else
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured))
#End If
End Sub
<Fact()>
Public Sub ImplicitSelect7()
Assert.Throws(Of System.ArgumentException)(
Sub()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s [|As|] Long In q Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
End Sub)
#If False Then
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured))
#End If
End Sub
<Fact>
Public Sub ImplicitSelect8()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = [|From s In q|]
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By [|x|],
x,
x Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x,
[|x|],
x Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x,
x,
[|x|] Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x,
x,
x Descending
Order By [|x|] Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In [|q|]
Order By x,
x,
x Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = [|From x In q
Order By x,
x,
x Descending
Order By x Descending
Select y = x|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy7()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From z In q
Select x = [|z|]
Order By x,
x,
x Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, z, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Query6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In q
Where [|s1 > y|]
System.Console.WriteLine(y)
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select10()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble1
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble2
Return Me
End Function
End Class
Class QueryAble2
Public Function [Select](Of T, U)(x As Func(Of T, U)) As QueryAble2
Return Me
End Function
End Class
Module C
Sub Main()
Dim q As New QueryAble1()
Dim q1 As Object = From s1 In q
Where 10 > s2
Select s1.MaxValue,
s2 = [|s1|],
s3 = s1 + 1
Select s2 + s3
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, MaxValue, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Let1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Let s2 = [|s1|],
s3 = s1 + 1
Let s4 = s2 + s3
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Let2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Let s2 = s1,
s3 = [|s1 + 1|]
Let s4 = s2 + s3
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Let3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Let s2 = s1,
s3 = s1 + 1
Let s4 = [|s2 + s3|]
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In qi
From s2 In [|s1|],
s3 In s1
From s4 In s2
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In q
from s2 In s1,
s3 In [|s2|]
From s4 In s3
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In q
from s2 In s1,
s3 In s2
From s4 In [|s3|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In q
from s2 In s1,
s3 In s2
Let s4 = [|s3|], s5 = s4
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4, s5", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In q
from s2 In s1,
s3 In s2
Select s4 = [|s3|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s1 In q Select s1+1
From s2 In [|q|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In [|qb|]
Join s3 In qs
On s2 Equals s3
On s1 Equals s2
Join s4 In qu
On s4 Equals s1
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In [|qs|]
On s2 Equals s3
On s1 Equals s2
Join s4 In qu
On s4 Equals s1
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In qs
On s2 Equals s3
On s1 Equals s2
Join s4 In [|qu|]
On s4 Equals s1
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In qs
On s2 Equals s3
On s1 Equals s2
Let s4 = [|s3|], s5 = s4
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4, s5", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In qs
On s2 Equals s3
On s1 Equals s2
Select s4 = [|s3|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In qs
On [|s2|] Equals s3
On s1 Equals s2
Select s4 = s3
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupBy1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s1 In [|qi|]
Group i1=s1
By k1=s1
Into Group, Count(), c1=Count(i1)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s1, i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupBy2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = [|From s1 In qi
Group i1=s1
By k1=s1
Into Group, Count(), c1=Count(i1)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, s1, i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupBy3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s1 In qi
Group i1=s1
By k1=s1
Into Group, Count(), c1=Count([|i1|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("i1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupBy4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s1 In qi
Group By k1=[|s1|]
Into Group, Count(), c1=Count(s1)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In [|qb|]
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count(s2)
Group Join s4 In qu
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In qb
Group Join s3 In [|qs|]
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count(s2)
Group Join s4 In qu
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In qb
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count(s2)
Group Join s4 In [|qu|]
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In qb
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals [|s2|]
Into c2 = Count(s2)
Group Join s4 In qu
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In qb
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count([|s2|])
Group Join s4 In qu
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = [|From s1 In qi
Group Join s2 In qb
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count(s2)
Group Join s4 In qu
On s4 Equals s1
Into Group|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi, qb, qs, qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In [|qi|]
Let s2 = s1 + 1
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In [|qi|]
Let s2 = s1 + 1
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In qi
Let s2 = [|s1 + 1|]
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In qi
Let s2 = [|s1 + 1|]
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In qi
Let s2 = s1 + 1
Into Count([|s2|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count([|s2|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate7()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = [|Aggregate s1 In qi
Let s2 = s1 + 1
Into Count(s2)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate8()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = [|Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count(s2)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate9()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in [|qb|]
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate10()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in [|qb|]
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate11()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In [|qi|]
Let s2 = s1 + 1
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate12()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In [|qi|]
Let s2 = s1 + 1
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate13()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In qi
Let s2 = [|s1 + 1|]
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate14()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In qi
Let s2 = [|s1 + 1|]
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate15()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count([|s2|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate16()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count([|s2|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate17()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = [|From t1 in qb
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count(s2)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate18()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = [|From t1 in qb
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count(s2)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<WorkItem(543164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543164")>
<Fact()>
Public Sub LambdaFunctionInsideSkipClause()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Imports System.Linq
Module Module1
Sub Main(arr As String())
Dim q2 = From s1 In arr Skip [|Function() s1|]
End Sub
End Module
]]></file>
</compilation>,
errors:=<errors>
BC36594: Definition of method 'Skip' is not accessible in this context.
Dim q2 = From s1 In arr Skip Function() s1
~~~~
BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.
Dim q2 = From s1 In arr Skip Function() s1
~~~~~~~~~~~~~
</errors>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("arr", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("arr, q2, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<WorkItem(543164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543164")>
<Fact()>
Public Sub LambdaFunctionInsideSkipClause2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Imports System.Linq
Module Module1
Sub Main(arr As String())
Dim q2 = From s1 In arr Skip [|s1|]
End Sub
End Module
]]></file>
</compilation>,
errors:=<errors>
BC30451: 's1' is not declared. It may be inaccessible due to its protection level.
Dim q2 = From s1 In arr Skip s1
~~
</errors>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("arr", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("arr, q2, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
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
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Partial Public Class FlowAnalysisTests
<Fact>
Public Sub Query1()
Dim compilationDef =
<compilation name="QueryExpressions">
<file name="a.vb">
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
Sub Main()
Dim q As QueryAble
Dim q1 As Object = From s In q Where 2 > s
Dim x1, x2, x3, x4 As Object
Dim qq As New QueryAble()
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'q' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q1 As Object = From s In q Where 2 > s
~
BC42104: Variable 'x1' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
~~
BC42104: Variable 'x2' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
~~
BC42104: Variable 'x3' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
~~
BC42104: Variable 'x4' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim q2 As Object = From s In qq Where x1 > s Where x2 > s Where x3 > s Select CInt(x4) + s
~~
</expected>)
End Sub
<Fact>
Public Sub Query2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In q
Where [|s1 > 0|]
Where 10 > s1 + y
Where DirectCast(Function()
System.Console.WriteLine(s1)
Return True
End Function, Func(Of Boolean)).Invoke()
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact>
Public Sub Query3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In [|q|]
Where s1 > 0
Where 10 > s1 + y
Where DirectCast(Function()
System.Console.WriteLine(s1)
Return True
End Function, Func(Of Boolean)).Invoke()
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
End Sub
<Fact>
Public Sub Query7()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = [|From s1 In q
Where s1 > 0
Where 10 > s1 + y
Where DirectCast(Function()
System.Console.WriteLine(s1)
Return True
End Function, Func(Of Boolean)).Invoke()|]
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Query4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In q
Where s1 > 0
Where 10 > s1 + y
Where [|DirectCast(Function()
Dim z As Integer = 0
y=s1
System.Console.WriteLine(s1+z)
Return True
End Function, Func(Of Boolean))|].Invoke()
System.Console.WriteLine(y)
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Query5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In q
Where s1 > 0
Where 10 > [|s1 + y|]
Where DirectCast(Function()
Dim z As Integer = 0
y=s1
System.Console.WriteLine(s1+z)
Return True
End Function, Func(Of Boolean)).Invoke()
System.Console.WriteLine(y)
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, y, s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select [|s1|]
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Dim flowsIn = dataFlowAnalysisResults.DataFlowsIn(0)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Same(flowsIn, dataFlowAnalysisResults.ReadInside(0))
Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Dim ss = dataFlowAnalysisResults.WrittenOutside.Where(Function(s) s.Name.Equals("s1", StringComparison.OrdinalIgnoreCase))
Assert.Equal(ss(0).Name, ss(1).Name)
Assert.NotEqual(ss(0), ss(1))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = [|From s1 In q
Select s1
Where 10 > s1|]
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal("s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.NotSame(dataFlowAnalysisResults.VariablesDeclared(0), dataFlowAnalysisResults.VariablesDeclared(1))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select s1 = [|s1|]
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.NotSame(dataFlowAnalysisResults.ReadInside(0), GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)(1))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select s2 = [|s1|]
Where 10 > s2
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select [|s1 + 1|]
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In [|q|]
Select s1 + 1
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select7()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In [|q|]
Select 1
Where 10 > s1
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select8()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select s2 = [|s1|]
Where 10 > s2
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select9()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Select s2 = [|s1|]
Where 10 > s2
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub ImplicitSelect1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Long In [|q|] Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub ImplicitSelect2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Long In [|q|] Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub ImplicitSelect3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As Long In [|q|] Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact()>
Public Sub ImplicitSelect4()
Assert.Throws(Of System.ArgumentException)(
Sub()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s [|As Long|] In q Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
End Sub)
#If False Then
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured))
#End If
End Sub
<Fact>
Public Sub ImplicitSelect5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = [|From s As Long In q Where s > 1|]
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact()>
Public Sub ImplicitSelect6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s As [|Long|] In q Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
#If True Then
Assert.False(dataFlowAnalysisResults.Succeeded)
#Else
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured))
#End If
End Sub
<Fact()>
Public Sub ImplicitSelect7()
Assert.Throws(Of System.ArgumentException)(
Sub()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s [|As|] Long In q Where s > 1
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
End Sub)
#If False Then
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.Captured))
#End If
End Sub
<Fact>
Public Sub ImplicitSelect8()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("Select")
Return Me
End Function
Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble
System.Console.WriteLine("Where")
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble
System.Console.WriteLine("[Select]")
Return this
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble
System.Console.WriteLine("[Where]")
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = [|From s In q|]
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By [|x|],
x,
x Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x,
[|x|],
x Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x,
x,
[|x|] Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In q
Order By x,
x,
x Descending
Order By [|x|] Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From x In [|q|]
Order By x,
x,
x Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = [|From x In q
Order By x,
x,
x Descending
Order By x Descending
Select y = x|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub OrderBy7()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenBy(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
Public Function OrderByDescending(x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function ThenByDescending(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Module Program
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From z In q
Select x = [|z|]
Order By x,
x,
x Descending
Order By x Descending
Select y = x
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, z, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Query6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble
Return Me
End Function
End Class
Class C
Sub Main(args As String())
Dim q As New QueryAble()
Dim y As Integer = 0
Dim q1 As Object = From s1 In q
Where [|s1 > y|]
System.Console.WriteLine(y)
End Sub
End Class
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("y, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("Me, args, q, y, q1, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Select10()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Class QueryAble1
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble1
Return Me
End Function
Public Function Where(x As Func(Of Integer, Byte)) As QueryAble2
Return Me
End Function
End Class
Class QueryAble2
Public Function [Select](Of T, U)(x As Func(Of T, U)) As QueryAble2
Return Me
End Function
End Class
Module C
Sub Main()
Dim q As New QueryAble1()
Dim q1 As Object = From s1 In q
Where 10 > s2
Select s1.MaxValue,
s2 = [|s1|],
s3 = s1 + 1
Select s2 + s3
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, MaxValue, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Let1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Let s2 = [|s1|],
s3 = s1 + 1
Let s4 = s2 + s3
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Let2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Let s2 = s1,
s3 = [|s1 + 1|]
Let s4 = s2 + s3
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Let3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble
Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return Me
End Function
End Class
Module Module1
<System.Runtime.CompilerServices.Extension()>
Public Function [Select](Of T, S)(this As QueryAble, x As Func(Of T, S)) As QueryAble
System.Console.WriteLine("[Select] {0}", x)
Return this
End Function
Sub Main()
Dim q As New QueryAble()
Dim q1 As Object = From s1 In q
Let s2 = s1,
s3 = s1 + 1
Let s4 = [|s2 + s3|]
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In qi
From s2 In [|s1|],
s3 In s1
From s4 In s2
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In q
from s2 In s1,
s3 In [|s2|]
From s4 In s3
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In q
from s2 In s1,
s3 In s2
From s4 In [|s3|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In q
from s2 In s1,
s3 In s2
Let s4 = [|s3|], s5 = s4
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4, s5", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0)
Dim q1 As Object = From s1 In q
from s2 In s1,
s3 In s2
Select s4 = [|s3|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub From6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R)
System.Console.WriteLine("SelectMany {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim q As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s1 In q Select s1+1
From s2 In [|q|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("q, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("q, q1, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("q", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In [|qb|]
Join s3 In qs
On s2 Equals s3
On s1 Equals s2
Join s4 In qu
On s4 Equals s1
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In [|qs|]
On s2 Equals s3
On s1 Equals s2
Join s4 In qu
On s4 Equals s1
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In qs
On s2 Equals s3
On s1 Equals s2
Join s4 In [|qu|]
On s4 Equals s1
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In qs
On s2 Equals s3
On s1 Equals s2
Let s4 = [|s3|], s5 = s4
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4, s5", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In qs
On s2 Equals s3
On s1 Equals s2
Select s4 = [|s3|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Join6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R)
System.Console.WriteLine("Join {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Join s2 In qb
Join s3 In qs
On [|s2|] Equals s3
On s1 Equals s2
Select s4 = s3
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupBy1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s1 In [|qi|]
Group i1=s1
By k1=s1
Into Group, Count(), c1=Count(i1)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s1, i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupBy2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = [|From s1 In qi
Group i1=s1
By k1=s1
Into Group, Count(), c1=Count(i1)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, s1, i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupBy3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s1 In qi
Group i1=s1
By k1=s1
Into Group, Count(), c1=Count([|i1|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("i1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("i1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, i1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupBy4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy {0}", item)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupBy ")
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = From s1 In qi
Group By k1=[|s1|]
Into Group, Count(), c1=Count(s1)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, k1, Group, Count, c1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In [|qb|]
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count(s2)
Group Join s4 In qu
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In qb
Group Join s3 In [|qs|]
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count(s2)
Group Join s4 In qu
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qs", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In qb
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count(s2)
Group Join s4 In [|qu|]
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qu", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In qb
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals [|s2|]
Into c2 = Count(s2)
Group Join s4 In qu
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = From s1 In qi
Group Join s2 In qb
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count([|s2|])
Group Join s4 In qu
On s4 Equals s1
Into Group
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1, s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub GroupJoin6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R)
System.Console.WriteLine("GroupJoin {0}", x)
Return New QueryAble(Of R)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim qs As New QueryAble(Of Short)(0)
Dim qu As New QueryAble(Of UInteger)(0)
Dim ql As New QueryAble(Of Long)(0)
Dim q1 As Object = [|From s1 In qi
Group Join s2 In qb
Group Join s3 In qs
On s2 Equals s3
Into c1 = Count()
On s1 Equals s2
Into c2 = Count(s2)
Group Join s4 In qu
On s4 Equals s1
Into Group|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi, qb, qs, qu", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, qb, qs, qu, s1, s2, s3, s4", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, s2, s3, c1, c2, s4, Group", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, qs, qu, ql, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate1()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In [|qi|]
Let s2 = s1 + 1
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In [|qi|]
Let s2 = s1 + 1
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate3()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In qi
Let s2 = [|s1 + 1|]
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate4()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In qi
Let s2 = [|s1 + 1|]
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate5()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In qi
Let s2 = s1 + 1
Into Count([|s2|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate6()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count([|s2|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate7()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = [|Aggregate s1 In qi
Let s2 = s1 + 1
Into Count(s2)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate8()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim q1 As Object = [|Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count(s2)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate9()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in [|qb|]
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate10()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in [|qb|]
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate11()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In [|qi|]
Let s2 = s1 + 1
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate12()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In [|qi|]
Let s2 = s1 + 1
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate13()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In qi
Let s2 = [|s1 + 1|]
Into Count
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate14()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In qi
Let s2 = [|s1 + 1|]
Into Count, c = Count(s2)
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate15()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count([|s2|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate16()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = From t1 in qb
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count([|s2|])
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("qi, qb, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1, t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate17()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = [|From t1 in qb
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count(s2)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("t1, s1, s2, Count", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<Fact>
Public Sub Aggregate18()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Option Strict Off
Imports System
Class QueryAble(Of T)
Public ReadOnly v As Integer
Sub New(v As Integer)
Me.v = v
End Sub
Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S)
System.Console.WriteLine("Select {0}", x)
Return New QueryAble(Of S)(v + 1)
End Function
Public Function Count(Of S)(x As Func(Of T, S)) As Integer
Return 0
End Function
Public Function Count() As Integer
Return 0
End Function
End Class
Module Module1
Sub Main()
Dim qi As New QueryAble(Of Integer)(0)
Dim qb As New QueryAble(Of Byte)(0)
Dim q1 As Object = [|From t1 in qb
Aggregate s1 In qi
Let s2 = s1 + 1
Into Count, c = Count(s2)|]
End Sub
End Module
]]></file>
</compilation>)
Assert.Equal("t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal("qi, qb", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal("qi, qb, s1, s2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal("t1, s1, s2, Count, c", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("qi, qb, q1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal("qi", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<WorkItem(543164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543164")>
<Fact()>
Public Sub LambdaFunctionInsideSkipClause()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Imports System.Linq
Module Module1
Sub Main(arr As String())
Dim q2 = From s1 In arr Skip [|Function() s1|]
End Sub
End Module
]]></file>
</compilation>,
errors:=<errors>
BC36594: Definition of method 'Skip' is not accessible in this context.
Dim q2 = From s1 In arr Skip Function() s1
~~~~
BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type.
Dim q2 = From s1 In arr Skip Function() s1
~~~~~~~~~~~~~
</errors>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("arr", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("arr, q2, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
<WorkItem(543164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543164")>
<Fact()>
Public Sub LambdaFunctionInsideSkipClause2()
Dim dataFlowAnalysisResults = CompileAndAnalyzeDataFlow(
<compilation>
<file name="a.b"><![CDATA[
Imports System
Imports System.Linq
Module Module1
Sub Main(arr As String())
Dim q2 = From s1 In arr Skip [|s1|]
End Sub
End Module
]]></file>
</compilation>,
errors:=<errors>
BC30451: 's1' is not declared. It may be inaccessible due to its protection level.
Dim q2 = From s1 In arr Skip s1
~~
</errors>)
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside))
Assert.Equal("arr", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside))
Assert.Equal("arr, q2, s1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowAnalysisResults.Captured))
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/EditorFeatures/Test/Workspaces/ProjectCacheHostServiceFactoryTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
[UseExportProvider]
public class ProjectCacheHostServiceFactoryTests
{
private static void Test(Action<IProjectCacheHostService, ProjectId, ICachedObjectOwner, ObjectReference<object>> action)
{
// Putting cacheService.CreateStrongReference in a using statement
// creates a temporary local that isn't collected in Debug builds
// Wrapping it in a lambda allows it to get collected.
var cacheService = new ProjectCacheService(null, TimeSpan.MaxValue);
var projectId = ProjectId.CreateNewId();
var owner = new Owner();
var instance = ObjectReference.CreateFromFactory(() => new object());
action(cacheService, projectId, owner, instance);
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheKeepsObjectAlive1()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
instance.UseReference(i => cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, i));
instance.AssertHeld();
}
instance.AssertReleased();
GC.KeepAlive(owner);
});
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheKeepsObjectAlive2()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
instance.UseReference(i => cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, i));
instance.AssertHeld();
}
instance.AssertReleased();
GC.KeepAlive(owner);
});
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected1()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, instance);
owner = null;
instance.AssertReleased();
}
});
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected2()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, instance);
owner = null;
instance.AssertReleased();
}
});
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestImplicitCacheKeepsObjectAlive1()
{
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cacheService = new ProjectCacheService(workspace, TimeSpan.MaxValue);
var reference = ObjectReference.CreateFromFactory(() => new object());
reference.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, r));
reference.AssertHeld();
GC.KeepAlive(cacheService);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/14592")]
public void TestImplicitCacheMonitoring()
{
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cacheService = new ProjectCacheService(workspace, TimeSpan.FromMilliseconds(10));
var weak = PutObjectInImplicitCache(cacheService);
weak.AssertReleased();
GC.KeepAlive(cacheService);
}
private static ObjectReference<object> PutObjectInImplicitCache(ProjectCacheService cacheService)
{
var reference = ObjectReference.CreateFromFactory(() => new object());
reference.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, r));
return reference;
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestP2PReference()
{
var workspace = new AdhocWorkspace();
var project1 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj1", "proj1", LanguageNames.CSharp);
var project2 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj2", "proj2", LanguageNames.CSharp, projectReferences: SpecializedCollections.SingletonEnumerable(new ProjectReference(project1.Id)));
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { project1, project2 });
var solution = workspace.AddSolution(solutionInfo);
var instanceTracker = ObjectReference.CreateFromFactory(() => new object());
var cacheService = new ProjectCacheService(workspace, TimeSpan.MaxValue);
using (var cache = cacheService.EnableCaching(project2.Id))
{
instanceTracker.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(project1.Id, (object)null, r));
solution = null;
workspace.OnProjectRemoved(project1.Id);
workspace.OnProjectRemoved(project2.Id);
}
// make sure p2p reference doesn't go to implicit cache
instanceTracker.AssertReleased();
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestEjectFromImplicitCache()
{
var compilations = new List<Compilation>();
for (var i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++)
{
compilations.Add(CSharpCompilation.Create(i.ToString()));
}
var weakFirst = ObjectReference.Create(compilations[0]);
var weakLast = ObjectReference.Create(compilations[compilations.Count - 1]);
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cache = new ProjectCacheService(workspace, TimeSpan.MaxValue);
for (var i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++)
{
cache.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, compilations[i]);
}
#pragma warning disable IDE0059 // Unnecessary assignment of a value - testing weak reference to compilations
compilations = null;
#pragma warning restore IDE0059 // Unnecessary assignment of a value
weakFirst.AssertReleased();
weakLast.AssertHeld();
GC.KeepAlive(cache);
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheCompilationTwice()
{
var comp1 = CSharpCompilation.Create("1");
var comp2 = CSharpCompilation.Create("2");
var comp3 = CSharpCompilation.Create("3");
var weak3 = ObjectReference.Create(comp3);
var weak1 = ObjectReference.Create(comp1);
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cache = new ProjectCacheService(workspace, TimeSpan.MaxValue);
var key = ProjectId.CreateNewId();
var owner = new object();
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp1);
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp2);
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3);
// When we cache 3 again, 1 should stay in the cache
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3);
#pragma warning disable IDE0059 // Unnecessary assignment of a value - testing weak references to compilations
comp1 = null;
comp2 = null;
comp3 = null;
#pragma warning restore IDE0059 // Unnecessary assignment of a value
weak3.AssertHeld();
weak1.AssertHeld();
GC.KeepAlive(cache);
}
private class Owner : ICachedObjectOwner
{
object ICachedObjectOwner.CachedObject { get; set; }
}
private class MockHostServices : HostServices
{
public static readonly MockHostServices Instance = new MockHostServices();
private MockHostServices() { }
protected internal override HostWorkspaceServices CreateWorkspaceServices(Workspace workspace)
=> new MockHostWorkspaceServices(this, workspace);
}
private sealed class MockTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler
=> (SynchronizationContext.Current != null) ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Default;
}
private sealed class MockWorkspaceAsynchronousOperationListenerProvider : IWorkspaceAsynchronousOperationListenerProvider
{
public IAsynchronousOperationListener GetListener()
=> AsynchronousOperationListenerProvider.NullListener;
}
private class MockHostWorkspaceServices : HostWorkspaceServices
{
private readonly HostServices _hostServices;
private readonly Workspace _workspace;
private static readonly ITaskSchedulerProvider s_taskSchedulerProvider = new MockTaskSchedulerProvider();
private static readonly IWorkspaceAsynchronousOperationListenerProvider s_asyncListenerProvider = new MockWorkspaceAsynchronousOperationListenerProvider();
private readonly OptionServiceFactory.OptionService _optionService;
public MockHostWorkspaceServices(HostServices hostServices, Workspace workspace)
{
_hostServices = hostServices;
_workspace = workspace;
var globalOptionService = new GlobalOptionService(workspaceThreadingService: null, ImmutableArray<Lazy<IOptionProvider, LanguageMetadata>>.Empty, ImmutableArray<Lazy<IOptionPersisterProvider>>.Empty);
_optionService = new OptionServiceFactory.OptionService(globalOptionService, this);
}
public override HostServices HostServices => _hostServices;
public override Workspace Workspace => _workspace;
public override IEnumerable<TLanguageService> FindLanguageServices<TLanguageService>(MetadataFilter filter)
=> ImmutableArray<TLanguageService>.Empty;
public override TWorkspaceService GetService<TWorkspaceService>()
{
if (s_taskSchedulerProvider is TWorkspaceService)
{
return (TWorkspaceService)s_taskSchedulerProvider;
}
if (s_asyncListenerProvider is TWorkspaceService)
{
return (TWorkspaceService)s_asyncListenerProvider;
}
if (_optionService is TWorkspaceService workspaceOptionService)
{
return workspaceOptionService;
}
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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
[UseExportProvider]
public class ProjectCacheHostServiceFactoryTests
{
private static void Test(Action<IProjectCacheHostService, ProjectId, ICachedObjectOwner, ObjectReference<object>> action)
{
// Putting cacheService.CreateStrongReference in a using statement
// creates a temporary local that isn't collected in Debug builds
// Wrapping it in a lambda allows it to get collected.
var cacheService = new ProjectCacheService(null, TimeSpan.MaxValue);
var projectId = ProjectId.CreateNewId();
var owner = new Owner();
var instance = ObjectReference.CreateFromFactory(() => new object());
action(cacheService, projectId, owner, instance);
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheKeepsObjectAlive1()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
instance.UseReference(i => cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, i));
instance.AssertHeld();
}
instance.AssertReleased();
GC.KeepAlive(owner);
});
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheKeepsObjectAlive2()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
instance.UseReference(i => cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, i));
instance.AssertHeld();
}
instance.AssertReleased();
GC.KeepAlive(owner);
});
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected1()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, instance);
owner = null;
instance.AssertReleased();
}
});
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected2()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, instance);
owner = null;
instance.AssertReleased();
}
});
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestImplicitCacheKeepsObjectAlive1()
{
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cacheService = new ProjectCacheService(workspace, TimeSpan.MaxValue);
var reference = ObjectReference.CreateFromFactory(() => new object());
reference.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, r));
reference.AssertHeld();
GC.KeepAlive(cacheService);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/14592")]
public void TestImplicitCacheMonitoring()
{
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cacheService = new ProjectCacheService(workspace, TimeSpan.FromMilliseconds(10));
var weak = PutObjectInImplicitCache(cacheService);
weak.AssertReleased();
GC.KeepAlive(cacheService);
}
private static ObjectReference<object> PutObjectInImplicitCache(ProjectCacheService cacheService)
{
var reference = ObjectReference.CreateFromFactory(() => new object());
reference.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, r));
return reference;
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestP2PReference()
{
var workspace = new AdhocWorkspace();
var project1 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj1", "proj1", LanguageNames.CSharp);
var project2 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj2", "proj2", LanguageNames.CSharp, projectReferences: SpecializedCollections.SingletonEnumerable(new ProjectReference(project1.Id)));
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { project1, project2 });
var solution = workspace.AddSolution(solutionInfo);
var instanceTracker = ObjectReference.CreateFromFactory(() => new object());
var cacheService = new ProjectCacheService(workspace, TimeSpan.MaxValue);
using (var cache = cacheService.EnableCaching(project2.Id))
{
instanceTracker.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(project1.Id, (object)null, r));
solution = null;
workspace.OnProjectRemoved(project1.Id);
workspace.OnProjectRemoved(project2.Id);
}
// make sure p2p reference doesn't go to implicit cache
instanceTracker.AssertReleased();
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestEjectFromImplicitCache()
{
var compilations = new List<Compilation>();
for (var i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++)
{
compilations.Add(CSharpCompilation.Create(i.ToString()));
}
var weakFirst = ObjectReference.Create(compilations[0]);
var weakLast = ObjectReference.Create(compilations[compilations.Count - 1]);
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cache = new ProjectCacheService(workspace, TimeSpan.MaxValue);
for (var i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++)
{
cache.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, compilations[i]);
}
#pragma warning disable IDE0059 // Unnecessary assignment of a value - testing weak reference to compilations
compilations = null;
#pragma warning restore IDE0059 // Unnecessary assignment of a value
weakFirst.AssertReleased();
weakLast.AssertHeld();
GC.KeepAlive(cache);
}
[WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")]
[ConditionalFact(typeof(x86))]
public void TestCacheCompilationTwice()
{
var comp1 = CSharpCompilation.Create("1");
var comp2 = CSharpCompilation.Create("2");
var comp3 = CSharpCompilation.Create("3");
var weak3 = ObjectReference.Create(comp3);
var weak1 = ObjectReference.Create(comp1);
var workspace = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
var cache = new ProjectCacheService(workspace, TimeSpan.MaxValue);
var key = ProjectId.CreateNewId();
var owner = new object();
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp1);
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp2);
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3);
// When we cache 3 again, 1 should stay in the cache
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3);
#pragma warning disable IDE0059 // Unnecessary assignment of a value - testing weak references to compilations
comp1 = null;
comp2 = null;
comp3 = null;
#pragma warning restore IDE0059 // Unnecessary assignment of a value
weak3.AssertHeld();
weak1.AssertHeld();
GC.KeepAlive(cache);
}
private class Owner : ICachedObjectOwner
{
object ICachedObjectOwner.CachedObject { get; set; }
}
private class MockHostServices : HostServices
{
public static readonly MockHostServices Instance = new MockHostServices();
private MockHostServices() { }
protected internal override HostWorkspaceServices CreateWorkspaceServices(Workspace workspace)
=> new MockHostWorkspaceServices(this, workspace);
}
private sealed class MockTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler
=> (SynchronizationContext.Current != null) ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Default;
}
private sealed class MockWorkspaceAsynchronousOperationListenerProvider : IWorkspaceAsynchronousOperationListenerProvider
{
public IAsynchronousOperationListener GetListener()
=> AsynchronousOperationListenerProvider.NullListener;
}
private class MockHostWorkspaceServices : HostWorkspaceServices
{
private readonly HostServices _hostServices;
private readonly Workspace _workspace;
private static readonly ITaskSchedulerProvider s_taskSchedulerProvider = new MockTaskSchedulerProvider();
private static readonly IWorkspaceAsynchronousOperationListenerProvider s_asyncListenerProvider = new MockWorkspaceAsynchronousOperationListenerProvider();
private readonly OptionServiceFactory.OptionService _optionService;
public MockHostWorkspaceServices(HostServices hostServices, Workspace workspace)
{
_hostServices = hostServices;
_workspace = workspace;
var globalOptionService = new GlobalOptionService(workspaceThreadingService: null, ImmutableArray<Lazy<IOptionProvider, LanguageMetadata>>.Empty, ImmutableArray<Lazy<IOptionPersisterProvider>>.Empty);
_optionService = new OptionServiceFactory.OptionService(globalOptionService, this);
}
public override HostServices HostServices => _hostServices;
public override Workspace Workspace => _workspace;
public override IEnumerable<TLanguageService> FindLanguageServices<TLanguageService>(MetadataFilter filter)
=> ImmutableArray<TLanguageService>.Empty;
public override TWorkspaceService GetService<TWorkspaceService>()
{
if (s_taskSchedulerProvider is TWorkspaceService)
{
return (TWorkspaceService)s_taskSchedulerProvider;
}
if (s_asyncListenerProvider is TWorkspaceService)
{
return (TWorkspaceService)s_asyncListenerProvider;
}
if (_optionService is TWorkspaceService workspaceOptionService)
{
return workspaceOptionService;
}
return default;
}
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/VisualStudio/Core/Def/Implementation/ChangeSignature/ChangeSignatureDialog.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.
#nullable disable
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
{
/// <summary>
/// Interaction logic for ChangeSignatureDialog.xaml
/// </summary>
internal partial class ChangeSignatureDialog : DialogWindow
{
private readonly ChangeSignatureDialogViewModel _viewModel;
// Expose localized strings for binding
public static string ChangeSignatureDialogTitle { get { return ServicesVSResources.Change_Signature; } }
public static string CurrentParameter { get { return ServicesVSResources.Current_parameter; } }
public static string Parameters { get { return ServicesVSResources.Parameters_colon2; } }
public static string PreviewMethodSignature { get { return ServicesVSResources.Preview_method_signature_colon; } }
public static string PreviewReferenceChanges { get { return ServicesVSResources.Preview_reference_changes; } }
public static string Remove { get { return ServicesVSResources.Re_move; } }
public static string Restore { get { return ServicesVSResources.Restore; } }
public static string Add { get { return ServicesVSResources.Add; } }
public static string OK { get { return ServicesVSResources.OK; } }
public static string Cancel { get { return ServicesVSResources.Cancel; } }
public static string WarningTypeDoesNotBind { get { return ServicesVSResources.Warning_colon_type_does_not_bind; } }
public static string WarningDuplicateParameterName { get { return ServicesVSResources.Warning_colon_duplicate_parameter_name; } }
public Brush ParameterText { get; }
public Brush RemovedParameterText { get; }
public Brush DisabledParameterForeground { get; }
public Brush DisabledParameterBackground { get; }
public Brush StrikethroughBrush { get; }
// Use C# Reorder Parameters helpTopic for C# and VB.
internal ChangeSignatureDialog(ChangeSignatureDialogViewModel viewModel)
: base(helpTopic: "vs.csharp.refactoring.reorder")
{
_viewModel = viewModel;
InitializeComponent();
// Set these headers explicitly because binding to DataGridTextColumn.Header is not
// supported.
modifierHeader.Header = ServicesVSResources.Modifier;
defaultHeader.Header = ServicesVSResources.Default_;
typeHeader.Header = ServicesVSResources.Type;
parameterHeader.Header = ServicesVSResources.Parameter;
callsiteHeader.Header = ServicesVSResources.Callsite;
indexHeader.Header = ServicesVSResources.Index;
ParameterText = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0x1E, 0x1E, 0x1E));
RemovedParameterText = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Colors.Gray);
DisabledParameterBackground = SystemParameters.HighContrast ? SystemColors.WindowBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xDF, 0xE7, 0xF3));
DisabledParameterForeground = SystemParameters.HighContrast ? SystemColors.GrayTextBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xA2, 0xA4, 0xA5));
Members.Background = SystemParameters.HighContrast ? SystemColors.WindowBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF));
StrikethroughBrush = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Colors.Red);
DataContext = viewModel;
Loaded += ChangeSignatureDialog_Loaded;
}
private void ChangeSignatureDialog_Loaded(object sender, RoutedEventArgs e)
=> Members.Focus();
private void OK_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.TrySubmit())
{
DialogResult = true;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
private void MoveUp_Click(object sender, EventArgs e)
{
MoveUp_UpdateSelectedIndex();
SetFocusToSelectedRow(false);
}
private void MoveUp_Click_FocusRow(object sender, EventArgs e)
{
MoveUp_UpdateSelectedIndex();
SetFocusToSelectedRow(true);
}
private void MoveUp_UpdateSelectedIndex()
{
var oldSelectedIndex = Members.SelectedIndex;
if (_viewModel.CanMoveUp && oldSelectedIndex >= 0)
{
_viewModel.MoveUp();
Members.Items.Refresh();
Members.SelectedIndex = oldSelectedIndex - 1;
}
}
private void MoveDown_Click(object sender, EventArgs e)
{
MoveDown_UpdateSelectedIndex();
SetFocusToSelectedRow(false);
}
private void MoveDown_Click_FocusRow(object sender, EventArgs e)
{
MoveDown_UpdateSelectedIndex();
SetFocusToSelectedRow(true);
}
private void MoveDown_UpdateSelectedIndex()
{
var oldSelectedIndex = Members.SelectedIndex;
if (_viewModel.CanMoveDown && oldSelectedIndex >= 0)
{
_viewModel.MoveDown();
Members.Items.Refresh();
Members.SelectedIndex = oldSelectedIndex + 1;
}
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.CanRemove)
{
_viewModel.Remove();
Members.Items.Refresh();
}
SetFocusToSelectedRow(true);
}
private void Restore_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.CanRestore)
{
_viewModel.Restore();
Members.Items.Refresh();
}
SetFocusToSelectedRow(true);
}
private void Add_Click(object sender, RoutedEventArgs e)
{
var addParameterViewModel = _viewModel.CreateAddParameterDialogViewModel();
var dialog = new AddParameterDialog(addParameterViewModel);
var result = dialog.ShowModal();
ChangeSignatureLogger.LogAddParameterDialogLaunched();
if (result.HasValue && result.Value)
{
ChangeSignatureLogger.LogAddParameterDialogCommitted();
var addedParameter = new AddedParameter(
addParameterViewModel.TypeSymbol,
addParameterViewModel.TypeName,
addParameterViewModel.ParameterName,
GetCallSiteKind(addParameterViewModel),
addParameterViewModel.IsCallsiteRegularValue ? addParameterViewModel.CallSiteValue : string.Empty,
addParameterViewModel.IsRequired,
addParameterViewModel.IsRequired ? string.Empty : addParameterViewModel.DefaultValue,
addParameterViewModel.TypeBinds);
_viewModel.AddParameter(addedParameter);
}
SetFocusToSelectedRow(false);
}
private static CallSiteKind GetCallSiteKind(AddParameterDialogViewModel addParameterViewModel)
{
if (addParameterViewModel.IsCallsiteInferred)
return CallSiteKind.Inferred;
if (addParameterViewModel.IsCallsiteOmitted)
return CallSiteKind.Omitted;
if (addParameterViewModel.IsCallsiteTodo)
return CallSiteKind.Todo;
Debug.Assert(addParameterViewModel.IsCallsiteRegularValue);
return addParameterViewModel.UseNamedArguments
? CallSiteKind.ValueWithName
: CallSiteKind.Value;
}
private void SetFocusToSelectedRow(bool focusRow)
{
if (Members.SelectedIndex >= 0)
{
if (Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) is not DataGridRow row)
{
Members.ScrollIntoView(Members.SelectedItem);
row = Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) as DataGridRow;
}
if (row != null && focusRow)
{
// This line is required primarily for accessibility purposes to ensure the screenreader always
// focuses on individual rows rather than the parent DataGrid.
Members.UpdateLayout();
FocusRow(row);
}
}
}
private static void FocusRow(DataGridRow row)
{
var cell = row.FindDescendant<DataGridCell>();
if (cell != null)
{
cell.Focus();
}
}
private void MoveSelectionUp_Click(object sender, EventArgs e)
{
var oldSelectedIndex = Members.SelectedIndex;
if (oldSelectedIndex > 0)
{
var potentialNewSelectedParameter = Members.Items[oldSelectedIndex - 1] as ChangeSignatureDialogViewModel.ParameterViewModel;
if (!potentialNewSelectedParameter.IsDisabled)
{
Members.SelectedIndex = oldSelectedIndex - 1;
}
}
SetFocusToSelectedRow(true);
}
private void MoveSelectionDown_Click(object sender, EventArgs e)
{
var oldSelectedIndex = Members.SelectedIndex;
if (oldSelectedIndex >= 0 && oldSelectedIndex < Members.Items.Count - 1)
{
Members.SelectedIndex = oldSelectedIndex + 1;
}
SetFocusToSelectedRow(true);
}
private void Members_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (Members.CurrentItem != null)
{
// When it has a valid value, CurrentItem is generally more up-to-date than SelectedIndex.
// For example, if the user clicks on an out of view item in the parameter list (i.e. the
// parameter list is long and the user scrolls to click another parameter farther down/up
// in the list), CurrentItem will update immediately while SelectedIndex will not.
Members.SelectedIndex = Members.Items.IndexOf(Members.CurrentItem);
}
if (Members.SelectedIndex == -1)
{
Members.SelectedIndex = _viewModel.GetStartingSelectionIndex();
}
SetFocusToSelectedRow(true);
}
private void ToggleRemovedState(object sender, ExecutedRoutedEventArgs e)
{
if (_viewModel.CanRemove)
{
_viewModel.Remove();
}
else if (_viewModel.CanRestore)
{
_viewModel.Restore();
}
Members.Items.Refresh();
SetFocusToSelectedRow(true);
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly ChangeSignatureDialog _dialog;
public TestAccessor(ChangeSignatureDialog dialog)
=> _dialog = dialog;
public ChangeSignatureDialogViewModel ViewModel => _dialog._viewModel;
public DataGrid Members => _dialog.Members;
public DialogButton OKButton => _dialog.OKButton;
public DialogButton CancelButton => _dialog.CancelButton;
public DialogButton DownButton => _dialog.DownButton;
public DialogButton UpButton => _dialog.UpButton;
public DialogButton AddButton => _dialog.AddButton;
public DialogButton RemoveButton => _dialog.RemoveButton;
public DialogButton RestoreButton => _dialog.RestoreButton;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
{
/// <summary>
/// Interaction logic for ChangeSignatureDialog.xaml
/// </summary>
internal partial class ChangeSignatureDialog : DialogWindow
{
private readonly ChangeSignatureDialogViewModel _viewModel;
// Expose localized strings for binding
public static string ChangeSignatureDialogTitle { get { return ServicesVSResources.Change_Signature; } }
public static string CurrentParameter { get { return ServicesVSResources.Current_parameter; } }
public static string Parameters { get { return ServicesVSResources.Parameters_colon2; } }
public static string PreviewMethodSignature { get { return ServicesVSResources.Preview_method_signature_colon; } }
public static string PreviewReferenceChanges { get { return ServicesVSResources.Preview_reference_changes; } }
public static string Remove { get { return ServicesVSResources.Re_move; } }
public static string Restore { get { return ServicesVSResources.Restore; } }
public static string Add { get { return ServicesVSResources.Add; } }
public static string OK { get { return ServicesVSResources.OK; } }
public static string Cancel { get { return ServicesVSResources.Cancel; } }
public static string WarningTypeDoesNotBind { get { return ServicesVSResources.Warning_colon_type_does_not_bind; } }
public static string WarningDuplicateParameterName { get { return ServicesVSResources.Warning_colon_duplicate_parameter_name; } }
public Brush ParameterText { get; }
public Brush RemovedParameterText { get; }
public Brush DisabledParameterForeground { get; }
public Brush DisabledParameterBackground { get; }
public Brush StrikethroughBrush { get; }
// Use C# Reorder Parameters helpTopic for C# and VB.
internal ChangeSignatureDialog(ChangeSignatureDialogViewModel viewModel)
: base(helpTopic: "vs.csharp.refactoring.reorder")
{
_viewModel = viewModel;
InitializeComponent();
// Set these headers explicitly because binding to DataGridTextColumn.Header is not
// supported.
modifierHeader.Header = ServicesVSResources.Modifier;
defaultHeader.Header = ServicesVSResources.Default_;
typeHeader.Header = ServicesVSResources.Type;
parameterHeader.Header = ServicesVSResources.Parameter;
callsiteHeader.Header = ServicesVSResources.Callsite;
indexHeader.Header = ServicesVSResources.Index;
ParameterText = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0x1E, 0x1E, 0x1E));
RemovedParameterText = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Colors.Gray);
DisabledParameterBackground = SystemParameters.HighContrast ? SystemColors.WindowBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xDF, 0xE7, 0xF3));
DisabledParameterForeground = SystemParameters.HighContrast ? SystemColors.GrayTextBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xA2, 0xA4, 0xA5));
Members.Background = SystemParameters.HighContrast ? SystemColors.WindowBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF));
StrikethroughBrush = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Colors.Red);
DataContext = viewModel;
Loaded += ChangeSignatureDialog_Loaded;
}
private void ChangeSignatureDialog_Loaded(object sender, RoutedEventArgs e)
=> Members.Focus();
private void OK_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.TrySubmit())
{
DialogResult = true;
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
private void MoveUp_Click(object sender, EventArgs e)
{
MoveUp_UpdateSelectedIndex();
SetFocusToSelectedRow(false);
}
private void MoveUp_Click_FocusRow(object sender, EventArgs e)
{
MoveUp_UpdateSelectedIndex();
SetFocusToSelectedRow(true);
}
private void MoveUp_UpdateSelectedIndex()
{
var oldSelectedIndex = Members.SelectedIndex;
if (_viewModel.CanMoveUp && oldSelectedIndex >= 0)
{
_viewModel.MoveUp();
Members.Items.Refresh();
Members.SelectedIndex = oldSelectedIndex - 1;
}
}
private void MoveDown_Click(object sender, EventArgs e)
{
MoveDown_UpdateSelectedIndex();
SetFocusToSelectedRow(false);
}
private void MoveDown_Click_FocusRow(object sender, EventArgs e)
{
MoveDown_UpdateSelectedIndex();
SetFocusToSelectedRow(true);
}
private void MoveDown_UpdateSelectedIndex()
{
var oldSelectedIndex = Members.SelectedIndex;
if (_viewModel.CanMoveDown && oldSelectedIndex >= 0)
{
_viewModel.MoveDown();
Members.Items.Refresh();
Members.SelectedIndex = oldSelectedIndex + 1;
}
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.CanRemove)
{
_viewModel.Remove();
Members.Items.Refresh();
}
SetFocusToSelectedRow(true);
}
private void Restore_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.CanRestore)
{
_viewModel.Restore();
Members.Items.Refresh();
}
SetFocusToSelectedRow(true);
}
private void Add_Click(object sender, RoutedEventArgs e)
{
var addParameterViewModel = _viewModel.CreateAddParameterDialogViewModel();
var dialog = new AddParameterDialog(addParameterViewModel);
var result = dialog.ShowModal();
ChangeSignatureLogger.LogAddParameterDialogLaunched();
if (result.HasValue && result.Value)
{
ChangeSignatureLogger.LogAddParameterDialogCommitted();
var addedParameter = new AddedParameter(
addParameterViewModel.TypeSymbol,
addParameterViewModel.TypeName,
addParameterViewModel.ParameterName,
GetCallSiteKind(addParameterViewModel),
addParameterViewModel.IsCallsiteRegularValue ? addParameterViewModel.CallSiteValue : string.Empty,
addParameterViewModel.IsRequired,
addParameterViewModel.IsRequired ? string.Empty : addParameterViewModel.DefaultValue,
addParameterViewModel.TypeBinds);
_viewModel.AddParameter(addedParameter);
}
SetFocusToSelectedRow(false);
}
private static CallSiteKind GetCallSiteKind(AddParameterDialogViewModel addParameterViewModel)
{
if (addParameterViewModel.IsCallsiteInferred)
return CallSiteKind.Inferred;
if (addParameterViewModel.IsCallsiteOmitted)
return CallSiteKind.Omitted;
if (addParameterViewModel.IsCallsiteTodo)
return CallSiteKind.Todo;
Debug.Assert(addParameterViewModel.IsCallsiteRegularValue);
return addParameterViewModel.UseNamedArguments
? CallSiteKind.ValueWithName
: CallSiteKind.Value;
}
private void SetFocusToSelectedRow(bool focusRow)
{
if (Members.SelectedIndex >= 0)
{
if (Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) is not DataGridRow row)
{
Members.ScrollIntoView(Members.SelectedItem);
row = Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) as DataGridRow;
}
if (row != null && focusRow)
{
// This line is required primarily for accessibility purposes to ensure the screenreader always
// focuses on individual rows rather than the parent DataGrid.
Members.UpdateLayout();
FocusRow(row);
}
}
}
private static void FocusRow(DataGridRow row)
{
var cell = row.FindDescendant<DataGridCell>();
if (cell != null)
{
cell.Focus();
}
}
private void MoveSelectionUp_Click(object sender, EventArgs e)
{
var oldSelectedIndex = Members.SelectedIndex;
if (oldSelectedIndex > 0)
{
var potentialNewSelectedParameter = Members.Items[oldSelectedIndex - 1] as ChangeSignatureDialogViewModel.ParameterViewModel;
if (!potentialNewSelectedParameter.IsDisabled)
{
Members.SelectedIndex = oldSelectedIndex - 1;
}
}
SetFocusToSelectedRow(true);
}
private void MoveSelectionDown_Click(object sender, EventArgs e)
{
var oldSelectedIndex = Members.SelectedIndex;
if (oldSelectedIndex >= 0 && oldSelectedIndex < Members.Items.Count - 1)
{
Members.SelectedIndex = oldSelectedIndex + 1;
}
SetFocusToSelectedRow(true);
}
private void Members_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (Members.CurrentItem != null)
{
// When it has a valid value, CurrentItem is generally more up-to-date than SelectedIndex.
// For example, if the user clicks on an out of view item in the parameter list (i.e. the
// parameter list is long and the user scrolls to click another parameter farther down/up
// in the list), CurrentItem will update immediately while SelectedIndex will not.
Members.SelectedIndex = Members.Items.IndexOf(Members.CurrentItem);
}
if (Members.SelectedIndex == -1)
{
Members.SelectedIndex = _viewModel.GetStartingSelectionIndex();
}
SetFocusToSelectedRow(true);
}
private void ToggleRemovedState(object sender, ExecutedRoutedEventArgs e)
{
if (_viewModel.CanRemove)
{
_viewModel.Remove();
}
else if (_viewModel.CanRestore)
{
_viewModel.Restore();
}
Members.Items.Refresh();
SetFocusToSelectedRow(true);
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly ChangeSignatureDialog _dialog;
public TestAccessor(ChangeSignatureDialog dialog)
=> _dialog = dialog;
public ChangeSignatureDialogViewModel ViewModel => _dialog._viewModel;
public DataGrid Members => _dialog.Members;
public DialogButton OKButton => _dialog.OKButton;
public DialogButton CancelButton => _dialog.CancelButton;
public DialogButton DownButton => _dialog.DownButton;
public DialogButton UpButton => _dialog.UpButton;
public DialogButton AddButton => _dialog.AddButton;
public DialogButton RemoveButton => _dialog.RemoveButton;
public DialogButton RestoreButton => _dialog.RestoreButton;
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/ConstKeywordRecommender.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.Declarations
''' <summary>
''' Recommends the "Const" keyword for the start of a statement.
''' </summary>
Friend Class ConstKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Const", VBFeaturesResources.Declares_and_defines_one_or_more_constants))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsMultiLineStatementContext, 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.Declarations
''' <summary>
''' Recommends the "Const" keyword for the start of a statement.
''' </summary>
Friend Class ConstKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Const", VBFeaturesResources.Declares_and_defines_one_or_more_constants))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsMultiLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/AbstractMemberScopedReferenceFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal abstract class AbstractMemberScopedReferenceFinder<TSymbol> : AbstractReferenceFinder<TSymbol>
where TSymbol : ISymbol
{
protected sealed override bool CanFind(TSymbol symbol)
=> true;
protected sealed override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
TSymbol symbol,
HashSet<string>? globalAliases,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var location = symbol.Locations.FirstOrDefault();
if (location == null || !location.IsInSource)
{
return SpecializedTasks.EmptyImmutableArray<Document>();
}
var document = project.GetDocument(location.SourceTree);
if (document == null)
{
return SpecializedTasks.EmptyImmutableArray<Document>();
}
if (documents != null && !documents.Contains(document))
{
return SpecializedTasks.EmptyImmutableArray<Document>();
}
return Task.FromResult(ImmutableArray.Create(document));
}
protected sealed override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
TSymbol symbol,
HashSet<string>? globalAliases,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var container = GetContainer(symbol);
if (container != null)
{
return await FindReferencesInContainerAsync(symbol, container, document, semanticModel, cancellationToken).ConfigureAwait(false);
}
if (symbol.ContainingType != null && symbol.ContainingType.IsScriptClass)
{
var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var tokens = root.DescendantTokens();
return await FindReferencesInTokensWithSymbolNameAsync(
symbol, document, semanticModel, tokens, cancellationToken).ConfigureAwait(false);
}
return ImmutableArray<FinderLocation>.Empty;
}
private static ISymbol? GetContainer(ISymbol symbol)
{
for (var current = symbol; current != null; current = current.ContainingSymbol)
{
if (current is IPropertySymbol)
{
return current;
}
// If this is an initializer for a property's backing field, then we want to
// search for results within the property itself.
if (current is IFieldSymbol field)
{
if (field.IsImplicitlyDeclared &&
field.AssociatedSymbol?.Kind == SymbolKind.Property)
{
return field.AssociatedSymbol;
}
else
{
return field;
}
}
if (current is IMethodSymbol method &&
method.MethodKind != MethodKind.AnonymousFunction &&
method.MethodKind != MethodKind.LocalFunction)
{
return method;
}
}
return null;
}
protected static ValueTask<ImmutableArray<FinderLocation>> FindReferencesInTokensWithSymbolNameAsync(
TSymbol symbol,
Document document,
SemanticModel semanticModel,
IEnumerable<SyntaxToken> tokens,
CancellationToken cancellationToken)
{
return FindReferencesInTokensWithSymbolNameAsync(
symbol, document, semanticModel, tokens, findParentNode: null, cancellationToken);
}
protected static ValueTask<ImmutableArray<FinderLocation>> FindReferencesInTokensWithSymbolNameAsync(
TSymbol symbol,
Document document,
SemanticModel semanticModel,
IEnumerable<SyntaxToken> tokens,
Func<SyntaxToken, SyntaxNode>? findParentNode,
CancellationToken cancellationToken)
{
var name = symbol.Name;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var symbolsMatch = GetStandardSymbolsMatchFunction(symbol, findParentNode, document.Project.Solution, cancellationToken);
return FindReferencesInTokensAsync(
document,
semanticModel,
tokens,
t => IdentifiersMatch(syntaxFacts, name, t),
symbolsMatch,
cancellationToken);
}
private ValueTask<ImmutableArray<FinderLocation>> FindReferencesInContainerAsync(
TSymbol symbol,
ISymbol container,
Document document,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return FindReferencesInContainerAsync(
symbol, container, document, semanticModel, findParentNode: null, cancellationToken);
}
private ValueTask<ImmutableArray<FinderLocation>> FindReferencesInContainerAsync(
TSymbol symbol,
ISymbol container,
Document document,
SemanticModel semanticModel,
Func<SyntaxToken, SyntaxNode>? findParentNode,
CancellationToken cancellationToken)
{
var service = document.GetRequiredLanguageService<ISymbolDeclarationService>();
var declarations = service.GetDeclarations(container);
var tokens = declarations.SelectMany(r => r.GetSyntax(cancellationToken).DescendantTokens());
var name = symbol.Name;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var symbolsMatch = GetStandardSymbolsMatchFunction(symbol, findParentNode, document.Project.Solution, cancellationToken);
var tokensMatch = GetTokensMatchFunction(syntaxFacts, name);
return FindReferencesInTokensAsync(
document,
semanticModel,
tokens,
tokensMatch,
symbolsMatch,
cancellationToken);
}
protected abstract Func<SyntaxToken, bool> GetTokensMatchFunction(ISyntaxFactsService syntaxFacts, string name);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal abstract class AbstractMemberScopedReferenceFinder<TSymbol> : AbstractReferenceFinder<TSymbol>
where TSymbol : ISymbol
{
protected sealed override bool CanFind(TSymbol symbol)
=> true;
protected sealed override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
TSymbol symbol,
HashSet<string>? globalAliases,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var location = symbol.Locations.FirstOrDefault();
if (location == null || !location.IsInSource)
{
return SpecializedTasks.EmptyImmutableArray<Document>();
}
var document = project.GetDocument(location.SourceTree);
if (document == null)
{
return SpecializedTasks.EmptyImmutableArray<Document>();
}
if (documents != null && !documents.Contains(document))
{
return SpecializedTasks.EmptyImmutableArray<Document>();
}
return Task.FromResult(ImmutableArray.Create(document));
}
protected sealed override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
TSymbol symbol,
HashSet<string>? globalAliases,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
var container = GetContainer(symbol);
if (container != null)
{
return await FindReferencesInContainerAsync(symbol, container, document, semanticModel, cancellationToken).ConfigureAwait(false);
}
if (symbol.ContainingType != null && symbol.ContainingType.IsScriptClass)
{
var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var tokens = root.DescendantTokens();
return await FindReferencesInTokensWithSymbolNameAsync(
symbol, document, semanticModel, tokens, cancellationToken).ConfigureAwait(false);
}
return ImmutableArray<FinderLocation>.Empty;
}
private static ISymbol? GetContainer(ISymbol symbol)
{
for (var current = symbol; current != null; current = current.ContainingSymbol)
{
if (current is IPropertySymbol)
{
return current;
}
// If this is an initializer for a property's backing field, then we want to
// search for results within the property itself.
if (current is IFieldSymbol field)
{
if (field.IsImplicitlyDeclared &&
field.AssociatedSymbol?.Kind == SymbolKind.Property)
{
return field.AssociatedSymbol;
}
else
{
return field;
}
}
if (current is IMethodSymbol method &&
method.MethodKind != MethodKind.AnonymousFunction &&
method.MethodKind != MethodKind.LocalFunction)
{
return method;
}
}
return null;
}
protected static ValueTask<ImmutableArray<FinderLocation>> FindReferencesInTokensWithSymbolNameAsync(
TSymbol symbol,
Document document,
SemanticModel semanticModel,
IEnumerable<SyntaxToken> tokens,
CancellationToken cancellationToken)
{
return FindReferencesInTokensWithSymbolNameAsync(
symbol, document, semanticModel, tokens, findParentNode: null, cancellationToken);
}
protected static ValueTask<ImmutableArray<FinderLocation>> FindReferencesInTokensWithSymbolNameAsync(
TSymbol symbol,
Document document,
SemanticModel semanticModel,
IEnumerable<SyntaxToken> tokens,
Func<SyntaxToken, SyntaxNode>? findParentNode,
CancellationToken cancellationToken)
{
var name = symbol.Name;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var symbolsMatch = GetStandardSymbolsMatchFunction(symbol, findParentNode, document.Project.Solution, cancellationToken);
return FindReferencesInTokensAsync(
document,
semanticModel,
tokens,
t => IdentifiersMatch(syntaxFacts, name, t),
symbolsMatch,
cancellationToken);
}
private ValueTask<ImmutableArray<FinderLocation>> FindReferencesInContainerAsync(
TSymbol symbol,
ISymbol container,
Document document,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return FindReferencesInContainerAsync(
symbol, container, document, semanticModel, findParentNode: null, cancellationToken);
}
private ValueTask<ImmutableArray<FinderLocation>> FindReferencesInContainerAsync(
TSymbol symbol,
ISymbol container,
Document document,
SemanticModel semanticModel,
Func<SyntaxToken, SyntaxNode>? findParentNode,
CancellationToken cancellationToken)
{
var service = document.GetRequiredLanguageService<ISymbolDeclarationService>();
var declarations = service.GetDeclarations(container);
var tokens = declarations.SelectMany(r => r.GetSyntax(cancellationToken).DescendantTokens());
var name = symbol.Name;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var symbolsMatch = GetStandardSymbolsMatchFunction(symbol, findParentNode, document.Project.Solution, cancellationToken);
var tokensMatch = GetTokensMatchFunction(syntaxFacts, name);
return FindReferencesInTokensAsync(
document,
semanticModel,
tokens,
tokensMatch,
symbolsMatch,
cancellationToken);
}
protected abstract Func<SyntaxToken, bool> GetTokensMatchFunction(ISyntaxFactsService syntaxFacts, string name);
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItem.AbstractGenerateCodeItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public abstract class AbstractGenerateCodeItem : RoslynNavigationBarItem, IEquatable<AbstractGenerateCodeItem>
{
public readonly SymbolKey DestinationTypeSymbolKey;
protected AbstractGenerateCodeItem(RoslynNavigationBarItemKind kind, string text, Glyph glyph, SymbolKey destinationTypeSymbolKey)
: base(kind, text, glyph, bolded: false, grayed: false, indent: 0, childItems: default)
{
DestinationTypeSymbolKey = destinationTypeSymbolKey;
}
public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
public bool Equals(AbstractGenerateCodeItem? other)
=> base.Equals(other) &&
DestinationTypeSymbolKey.Equals(other.DestinationTypeSymbolKey);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public abstract class AbstractGenerateCodeItem : RoslynNavigationBarItem, IEquatable<AbstractGenerateCodeItem>
{
public readonly SymbolKey DestinationTypeSymbolKey;
protected AbstractGenerateCodeItem(RoslynNavigationBarItemKind kind, string text, Glyph glyph, SymbolKey destinationTypeSymbolKey)
: base(kind, text, glyph, bolded: false, grayed: false, indent: 0, childItems: default)
{
DestinationTypeSymbolKey = destinationTypeSymbolKey;
}
public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
public bool Equals(AbstractGenerateCodeItem? other)
=> base.Equals(other) &&
DestinationTypeSymbolKey.Equals(other.DestinationTypeSymbolKey);
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Model/Node.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Xml.Serialization;
namespace CSharpSyntaxGenerator
{
public class Node : TreeType
{
[XmlAttribute]
public string Root;
[XmlAttribute]
public string Errors;
[XmlElement(ElementName = "Kind", Type = typeof(Kind))]
public List<Kind> Kinds = new List<Kind>();
public readonly List<Field> Fields = new List<Field>();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Xml.Serialization;
namespace CSharpSyntaxGenerator
{
public class Node : TreeType
{
[XmlAttribute]
public string Root;
[XmlAttribute]
public string Errors;
[XmlElement(ElementName = "Kind", Type = typeof(Kind))]
public List<Kind> Kinds = new List<Kind>();
public readonly List<Field> Fields = new List<Field>();
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/Core/Portable/InlineHints/IInlineHintsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.InlineHints
{
internal interface IInlineHintsService : ILanguageService
{
Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.InlineHints
{
internal interface IInlineHintsService : ILanguageService
{
Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/AttributeScopesKeywordRecommenderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class AttributeScopeKeywordRecommenderTests
Inherits RecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileTest()
VerifyRecommendationsContain(<File><|</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileAfterImportsTest()
VerifyRecommendationsContain(<File>
Imports Goo
<|</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileBeforeClassTest()
VerifyRecommendationsContain(<File>
<|
Class Goo
End Class</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileInsideClassTest()
VerifyRecommendationsAreExactly(<File>
Class Goo
<|
End Class</File>, {"Global"})
End Sub
<WorkItem(542207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542207")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileAtStartOfMalformedAttributeTest()
VerifyRecommendationsContain(<File><![CDATA[<|Assembly: AssemblyDelaySignAttribute(True)>]]></File>,
"Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesAtEndOfFileTest()
VerifyRecommendationsContain(<File>
Class goo
End Class
<|
</File>, "Assembly", "Module")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesAfterEolTest()
VerifyRecommendationsContain(<File>
Class goo
End Class
<
|
</File>, "Assembly", "Module")
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class AttributeScopeKeywordRecommenderTests
Inherits RecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileTest()
VerifyRecommendationsContain(<File><|</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileAfterImportsTest()
VerifyRecommendationsContain(<File>
Imports Goo
<|</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileBeforeClassTest()
VerifyRecommendationsContain(<File>
<|
Class Goo
End Class</File>, "Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileInsideClassTest()
VerifyRecommendationsAreExactly(<File>
Class Goo
<|
End Class</File>, {"Global"})
End Sub
<WorkItem(542207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542207")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesInFileAtStartOfMalformedAttributeTest()
VerifyRecommendationsContain(<File><![CDATA[<|Assembly: AssemblyDelaySignAttribute(True)>]]></File>,
"Assembly", "Module")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesAtEndOfFileTest()
VerifyRecommendationsContain(<File>
Class goo
End Class
<|
</File>, "Assembly", "Module")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AttributeScopesAfterEolTest()
VerifyRecommendationsContain(<File>
Class goo
End Class
<
|
</File>, "Assembly", "Module")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/EditorFeatures/Core.Wpf/Preview/PreviewFactoryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
[Export(typeof(IPreviewFactoryService)), Shared]
internal class PreviewFactoryService : AbstractPreviewFactoryService<IWpfDifferenceViewer>
{
private readonly IWpfDifferenceViewerFactoryService _differenceViewerService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewFactoryService(
IThreadingContext threadingContext,
ITextBufferFactoryService textBufferFactoryService,
IContentTypeRegistryService contentTypeRegistryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
ITextEditorFactoryService textEditorFactoryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
ITextDifferencingSelectorService differenceSelectorService,
IDifferenceBufferFactoryService differenceBufferService,
IWpfDifferenceViewerFactoryService differenceViewerService)
: base(threadingContext,
textBufferFactoryService,
contentTypeRegistryService,
projectionBufferFactoryService,
editorOptionsFactoryService,
differenceSelectorService,
differenceBufferService,
textEditorFactoryService.CreateTextViewRoleSet(
TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable))
{
_differenceViewerService = differenceViewerService;
}
protected override async Task<IWpfDifferenceViewer> CreateDifferenceViewAsync(IDifferenceBuffer diffBuffer, ITextViewRoleSet previewRoleSet, DifferenceViewMode mode, double zoomLevel, CancellationToken cancellationToken)
{
var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, previewRoleSet);
const string DiffOverviewMarginName = "deltadifferenceViewerOverview";
diffViewer.ViewMode = mode;
if (mode == DifferenceViewMode.RightViewOnly)
{
diffViewer.RightView.ZoomLevel *= zoomLevel;
diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
else if (mode == DifferenceViewMode.LeftViewOnly)
{
diffViewer.LeftView.ZoomLevel *= zoomLevel;
diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
else
{
Contract.ThrowIfFalse(mode == DifferenceViewMode.Inline);
diffViewer.InlineView.ZoomLevel *= zoomLevel;
diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
// Disable focus / tab stop for the diff viewer.
diffViewer.RightView.VisualElement.Focusable = false;
diffViewer.LeftView.VisualElement.Focusable = false;
diffViewer.InlineView.VisualElement.Focusable = false;
#pragma warning disable CA2007 // Consider calling ConfigureAwait on the awaited task (containing method uses JTF)
await diffViewer.SizeToFitAsync(ThreadingContext, cancellationToken: cancellationToken);
#pragma warning restore CA2007 // Consider calling ConfigureAwait on the awaited task
return diffViewer;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
[Export(typeof(IPreviewFactoryService)), Shared]
internal class PreviewFactoryService : AbstractPreviewFactoryService<IWpfDifferenceViewer>
{
private readonly IWpfDifferenceViewerFactoryService _differenceViewerService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewFactoryService(
IThreadingContext threadingContext,
ITextBufferFactoryService textBufferFactoryService,
IContentTypeRegistryService contentTypeRegistryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
ITextEditorFactoryService textEditorFactoryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
ITextDifferencingSelectorService differenceSelectorService,
IDifferenceBufferFactoryService differenceBufferService,
IWpfDifferenceViewerFactoryService differenceViewerService)
: base(threadingContext,
textBufferFactoryService,
contentTypeRegistryService,
projectionBufferFactoryService,
editorOptionsFactoryService,
differenceSelectorService,
differenceBufferService,
textEditorFactoryService.CreateTextViewRoleSet(
TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable))
{
_differenceViewerService = differenceViewerService;
}
protected override async Task<IWpfDifferenceViewer> CreateDifferenceViewAsync(IDifferenceBuffer diffBuffer, ITextViewRoleSet previewRoleSet, DifferenceViewMode mode, double zoomLevel, CancellationToken cancellationToken)
{
var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, previewRoleSet);
const string DiffOverviewMarginName = "deltadifferenceViewerOverview";
diffViewer.ViewMode = mode;
if (mode == DifferenceViewMode.RightViewOnly)
{
diffViewer.RightView.ZoomLevel *= zoomLevel;
diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
else if (mode == DifferenceViewMode.LeftViewOnly)
{
diffViewer.LeftView.ZoomLevel *= zoomLevel;
diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
else
{
Contract.ThrowIfFalse(mode == DifferenceViewMode.Inline);
diffViewer.InlineView.ZoomLevel *= zoomLevel;
diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed;
}
// Disable focus / tab stop for the diff viewer.
diffViewer.RightView.VisualElement.Focusable = false;
diffViewer.LeftView.VisualElement.Focusable = false;
diffViewer.InlineView.VisualElement.Focusable = false;
#pragma warning disable CA2007 // Consider calling ConfigureAwait on the awaited task (containing method uses JTF)
await diffViewer.SizeToFitAsync(ThreadingContext, cancellationToken: cancellationToken);
#pragma warning restore CA2007 // Consider calling ConfigureAwait on the awaited task
return diffViewer;
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PropertySymbols.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Property1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
}
static void Main(string[] args)
{
int temp = Program.[|Goo|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Property2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:Goo|}
{
get
{
return 1;
}
}
static void Main(string[] args)
{
int temp = Program.[|Go$$o|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyCascadeThroughInterface1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I
{
int {|Definition:$$P|} { get; }
}
class C : I
{
public int {|Definition:P|} { get; }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyCascadeThroughInterface2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I
{
int {|Definition:P|} { get; }
}
class C : I
{
public int {|Definition:$$P|} { get; }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:$$Area|} { get; }
}
class C1 : I1
{
public int {|Definition:Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:Area|} { get; }
}
class C1 : I1
{
public int {|Definition:$$Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int Definition:Area { get; }
}
class C1 : I1
{
public int Definition:Area { get { return 1; } }
}
class C2 : C1
{
public int {|Definition:$$Area|}
{
get
{
return base.Area;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:Area|} { get; }
}
class C1 : I1
{
public int {|Definition:Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|$$Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_ExplicitProperty1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface DD
{
int {|Definition:$$Prop|} { get; set; }
}
public class A : DD
{
int DD.{|Definition:Prop|}
{
get { return 1; }
set { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_ExplicitProperty2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface DD
{
int {|Definition:Prop|} { get; set; }
}
public class A : DD
{
int DD.{|Definition:$$Prop|}
{
get { return 1; }
set { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface1_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:$$Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface1_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:$$Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int {|Definition:$$Name|} { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T Name { get; set; }
int I2.{|Definition:Name|} { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface3_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:$$Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface3_FEature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:$$Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int {|Definition:Name|} { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T Name { get; set; }
int I2.{|Definition:$$Name|} { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:$$Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_PropertyFunctionValue1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Module Program
ReadOnly Property {|Definition:$$X|} As Integer ' Rename X to Y
Get
[|X|] = 1
End Get
End Property
End Module]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_PropertyFunctionValue2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Module Program
ReadOnly Property {|Definition:X|} As Integer ' Rename X to Y
Get
[|$$X|] = 1
End Get
End Property
End Module]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { $$[|{|Definition:P|}|] = 4 };
var b = new { P = "asdf" };
var c = new { [|P|] = 4 };
var d = new { P = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { [|P|] = 4 };
var b = new { P = "asdf" };
var c = new { $$[|{|Definition:P|}|] = 4 };
var d = new { P = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { P = 4 };
var b = new { $$[|{|Definition:P|}|] = "asdf" };
var c = new { P = 4 };
var d = new { [|P|] = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { P = 4 };
var b = new { [|P|] = "asdf" };
var c = new { P = 4 };
var d = new { $$[|{|Definition:P|}|] = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.at = New With {.s = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key {|Definition:a1|}}
Dim hello = query.First()
Console.WriteLine(hello.$$[|a1|].at.s)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.[|{|Definition:at|}|] = New With {.s = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key a1}
Dim hello = query.First()
Console.WriteLine(hello.a1.$$[|at|].s)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.at = New With {.[|{|Definition:s|}|] = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key a1}
Dim hello = query.First()
Console.WriteLine(hello.a1.at.$$[|s|])
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenPropertyAndField1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Property {|Definition:$$X|}()
Sub Goo()
Console.WriteLine([|_X|])
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenPropertyAndField2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Property {|Definition:X|}()
Sub Goo()
Console.WriteLine([|$$_X|])
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:$$X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:get_X|}(int y)
{
return base.[|get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:$$get_X|}(int y)
{
return base.[|get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:get_X|}(int y)
{
return base.[|$$get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_DefaultProperties(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Public Interface IA
Default Property Goo(ByVal x As Integer) As Integer
End Interface
Public Interface IC
Inherits IA
Default Overloads Property {|Definition:$$Goo|}(ByVal x As Long) As String ' Rename Goo to Bar
End Interface
Class M
Sub F(x As IC)
Dim y = x[||](1L)
Dim y2 = x(1)
End Sub
End Class
</Document>
<Document>
Class M2
Sub F(x As IC)
Dim y = x[||](1L)
Dim y2 = x(1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_DefaultProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Public Interface IA
Default Property {|Definition:$$Goo|}(ByVal x As Integer) As Integer
End Interface
Public Interface IC
Inherits IA
Default Overloads Property Goo(ByVal x As Long) As String ' Rename Goo to Bar
End Interface
Class M
Sub F(x As IC)
Dim y = x(1L)
Dim y2 = x[||](1)
End Sub
End Class
</Document>
<Document>
Class M2
Sub F(x As IC)
Dim y = x(1L)
Dim y2 = x[||](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpProperty_Cref(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
/// <see cref="[|Prop|]"/>
int {|Definition:$$Prop|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestProperty_ValueUsageInfo(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
set
{
}
}
static void Main(string[] args)
{
Console.WriteLine(Program.{|ValueUsageInfo.Read:[|Goo|]|});
Program.{|ValueUsageInfo.Write:[|Goo|]|} = 0;
Program.{|ValueUsageInfo.ReadWrite:[|Goo|]|} += 1;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestPropertyReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~P:N.C.[|P|]")]
namespace N
{
class C
{
public int {|Definition:$$P|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyUseInSourceGeneratedDocument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
namespace ConsoleApplication22
{
class C
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
}
}
}
</Document>
<DocumentFromSourceGenerator>
using System;
namespace ConsoleApplication22
{
class Program
{
static void Main(string[] args)
{
int temp = C.[|Goo|];
}
}
}
</DocumentFromSourceGenerator>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyInInterface(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P$$2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaFeature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P$$2|} { get; set; }
}
class C2_2 : I2
{
static int I2.P2 { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaFeature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int P2 { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P$$2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaAPI1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P$$2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaAPI2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P$$2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Property1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
}
static void Main(string[] args)
{
int temp = Program.[|Goo|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Property2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:Goo|}
{
get
{
return 1;
}
}
static void Main(string[] args)
{
int temp = Program.[|Go$$o|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyCascadeThroughInterface1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I
{
int {|Definition:$$P|} { get; }
}
class C : I
{
public int {|Definition:P|} { get; }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyCascadeThroughInterface2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I
{
int {|Definition:P|} { get; }
}
class C : I
{
public int {|Definition:$$P|} { get; }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:$$Area|} { get; }
}
class C1 : I1
{
public int {|Definition:Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:Area|} { get; }
}
class C1 : I1
{
public int {|Definition:$$Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int Definition:Area { get; }
}
class C1 : I1
{
public int Definition:Area { get { return 1; } }
}
class C2 : C1
{
public int {|Definition:$$Area|}
{
get
{
return base.Area;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:Area|} { get; }
}
class C1 : I1
{
public int {|Definition:Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|$$Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_ExplicitProperty1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface DD
{
int {|Definition:$$Prop|} { get; set; }
}
public class A : DD
{
int DD.{|Definition:Prop|}
{
get { return 1; }
set { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_ExplicitProperty2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface DD
{
int {|Definition:Prop|} { get; set; }
}
public class A : DD
{
int DD.{|Definition:$$Prop|}
{
get { return 1; }
set { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface1_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:$$Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface1_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:$$Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int {|Definition:$$Name|} { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T Name { get; set; }
int I2.{|Definition:Name|} { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface3_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:$$Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface3_FEature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:$$Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int {|Definition:Name|} { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T Name { get; set; }
int I2.{|Definition:$$Name|} { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:$$Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_PropertyFunctionValue1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Module Program
ReadOnly Property {|Definition:$$X|} As Integer ' Rename X to Y
Get
[|X|] = 1
End Get
End Property
End Module]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_PropertyFunctionValue2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Module Program
ReadOnly Property {|Definition:X|} As Integer ' Rename X to Y
Get
[|$$X|] = 1
End Get
End Property
End Module]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { $$[|{|Definition:P|}|] = 4 };
var b = new { P = "asdf" };
var c = new { [|P|] = 4 };
var d = new { P = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { [|P|] = 4 };
var b = new { P = "asdf" };
var c = new { $$[|{|Definition:P|}|] = 4 };
var d = new { P = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { P = 4 };
var b = new { $$[|{|Definition:P|}|] = "asdf" };
var c = new { P = 4 };
var d = new { [|P|] = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { P = 4 };
var b = new { [|P|] = "asdf" };
var c = new { P = 4 };
var d = new { $$[|{|Definition:P|}|] = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.at = New With {.s = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key {|Definition:a1|}}
Dim hello = query.First()
Console.WriteLine(hello.$$[|a1|].at.s)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.[|{|Definition:at|}|] = New With {.s = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key a1}
Dim hello = query.First()
Console.WriteLine(hello.a1.$$[|at|].s)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.at = New With {.[|{|Definition:s|}|] = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key a1}
Dim hello = query.First()
Console.WriteLine(hello.a1.at.$$[|s|])
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenPropertyAndField1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Property {|Definition:$$X|}()
Sub Goo()
Console.WriteLine([|_X|])
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenPropertyAndField2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Property {|Definition:X|}()
Sub Goo()
Console.WriteLine([|$$_X|])
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:$$X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:get_X|}(int y)
{
return base.[|get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:$$get_X|}(int y)
{
return base.[|get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:get_X|}(int y)
{
return base.[|$$get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_DefaultProperties(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Public Interface IA
Default Property Goo(ByVal x As Integer) As Integer
End Interface
Public Interface IC
Inherits IA
Default Overloads Property {|Definition:$$Goo|}(ByVal x As Long) As String ' Rename Goo to Bar
End Interface
Class M
Sub F(x As IC)
Dim y = x[||](1L)
Dim y2 = x(1)
End Sub
End Class
</Document>
<Document>
Class M2
Sub F(x As IC)
Dim y = x[||](1L)
Dim y2 = x(1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_DefaultProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Public Interface IA
Default Property {|Definition:$$Goo|}(ByVal x As Integer) As Integer
End Interface
Public Interface IC
Inherits IA
Default Overloads Property Goo(ByVal x As Long) As String ' Rename Goo to Bar
End Interface
Class M
Sub F(x As IC)
Dim y = x(1L)
Dim y2 = x[||](1)
End Sub
End Class
</Document>
<Document>
Class M2
Sub F(x As IC)
Dim y = x(1L)
Dim y2 = x[||](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpProperty_Cref(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
/// <see cref="[|Prop|]"/>
int {|Definition:$$Prop|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestProperty_ValueUsageInfo(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
set
{
}
}
static void Main(string[] args)
{
Console.WriteLine(Program.{|ValueUsageInfo.Read:[|Goo|]|});
Program.{|ValueUsageInfo.Write:[|Goo|]|} = 0;
Program.{|ValueUsageInfo.ReadWrite:[|Goo|]|} += 1;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestPropertyReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~P:N.C.[|P|]")]
namespace N
{
class C
{
public int {|Definition:$$P|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyUseInSourceGeneratedDocument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
namespace ConsoleApplication22
{
class C
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
}
}
}
</Document>
<DocumentFromSourceGenerator>
using System;
namespace ConsoleApplication22
{
class Program
{
static void Main(string[] args)
{
int temp = C.[|Goo|];
}
}
}
</DocumentFromSourceGenerator>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyInInterface(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P$$2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaFeature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P$$2|} { get; set; }
}
class C2_2 : I2
{
static int I2.P2 { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaFeature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int P2 { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P$$2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaAPI1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P$$2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaAPI2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P$$2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/VisualStudio/Core/Test/Debugging/VisualBasicBreakpointResolutionServiceTests.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.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Debugging
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Debugging
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.UnitTests.Debugging
<[UseExportProvider]>
Public Class VisualBasicBreakpointResolutionServiceTests
Public Async Function TestSpanWithLengthAsync(markup As XElement, length As Integer) As Task
Dim position As Integer? = Nothing
Dim expectedSpan As TextSpan? = Nothing
Dim source As String = Nothing
MarkupTestFile.GetPositionAndSpan(markup.NormalizedValue, source, position, expectedSpan)
Using workspace = TestWorkspace.CreateVisualBasic(source)
Dim document = workspace.CurrentSolution.Projects.First.Documents.First
Dim result As BreakpointResolutionResult = Await VisualBasicBreakpointResolutionService.GetBreakpointAsync(document, position.Value, length, CancellationToken.None)
Assert.True(expectedSpan.Value = result.TextSpan,
String.Format(vbCrLf & "Expected: {0} ""{1}""" & vbCrLf & "Actual: {2} ""{3}""",
expectedSpan.Value,
source.Substring(expectedSpan.Value.Start, expectedSpan.Value.Length),
result.TextSpan,
source.Substring(result.TextSpan.Start, result.TextSpan.Length)))
End Using
End Function
<WorkItem(876520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876520")>
<Fact>
Public Async Function TestBreakpointSpansMultipleMethods() As Task
' Normal case: debugger passing BP spans "sub Goo() end sub"
Await TestSpanWithLengthAsync(<text>
class C
[|$$sub Goo()|]
end sub
sub Bar()
end sub
end class</text>, 20)
' Rare case: debugger passing BP spans "sub Goo() end sub sub Bar() end sub"
Await TestSpanWithLengthAsync(<text>
class C
$$sub Goo()
end sub
[|sub Bar()|]
end sub
end class</text>, 35)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Debugging
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Debugging
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.UnitTests.Debugging
<[UseExportProvider]>
Public Class VisualBasicBreakpointResolutionServiceTests
Public Async Function TestSpanWithLengthAsync(markup As XElement, length As Integer) As Task
Dim position As Integer? = Nothing
Dim expectedSpan As TextSpan? = Nothing
Dim source As String = Nothing
MarkupTestFile.GetPositionAndSpan(markup.NormalizedValue, source, position, expectedSpan)
Using workspace = TestWorkspace.CreateVisualBasic(source)
Dim document = workspace.CurrentSolution.Projects.First.Documents.First
Dim result As BreakpointResolutionResult = Await VisualBasicBreakpointResolutionService.GetBreakpointAsync(document, position.Value, length, CancellationToken.None)
Assert.True(expectedSpan.Value = result.TextSpan,
String.Format(vbCrLf & "Expected: {0} ""{1}""" & vbCrLf & "Actual: {2} ""{3}""",
expectedSpan.Value,
source.Substring(expectedSpan.Value.Start, expectedSpan.Value.Length),
result.TextSpan,
source.Substring(result.TextSpan.Start, result.TextSpan.Length)))
End Using
End Function
<WorkItem(876520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876520")>
<Fact>
Public Async Function TestBreakpointSpansMultipleMethods() As Task
' Normal case: debugger passing BP spans "sub Goo() end sub"
Await TestSpanWithLengthAsync(<text>
class C
[|$$sub Goo()|]
end sub
sub Bar()
end sub
end class</text>, 20)
' Rare case: debugger passing BP spans "sub Goo() end sub sub Bar() end sub"
Await TestSpanWithLengthAsync(<text>
class C
$$sub Goo()
end sub
[|sub Bar()|]
end sub
end class</text>, 35)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/AbstractKeywordRecommender.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
Friend MustInherit Class AbstractKeywordRecommender
Implements IKeywordRecommender(Of VisualBasicSyntaxContext)
Public Function RecommendKeywords(
position As Integer,
context As VisualBasicSyntaxContext,
cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Implements IKeywordRecommender(Of VisualBasicSyntaxContext).RecommendKeywords
Return RecommendKeywords(context, cancellationToken)
End Function
Friend Function RecommendKeywords_Test(context As VisualBasicSyntaxContext) As ImmutableArray(Of RecommendedKeyword)
Return RecommendKeywords(context, CancellationToken.None)
End Function
Protected MustOverride Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
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
Friend MustInherit Class AbstractKeywordRecommender
Implements IKeywordRecommender(Of VisualBasicSyntaxContext)
Public Function RecommendKeywords(
position As Integer,
context As VisualBasicSyntaxContext,
cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Implements IKeywordRecommender(Of VisualBasicSyntaxContext).RecommendKeywords
Return RecommendKeywords(context, cancellationToken)
End Function
Friend Function RecommendKeywords_Test(context As VisualBasicSyntaxContext) As ImmutableArray(Of RecommendedKeyword)
Return RecommendKeywords(context, CancellationToken.None)
End Function
Protected MustOverride Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/CSharp/Portable/Wrapping/ChainedExpression/CSharpChainedExpressionWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Indentation;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Wrapping.ChainedExpression;
namespace Microsoft.CodeAnalysis.CSharp.Wrapping.ChainedExpression
{
internal class CSharpChainedExpressionWrapper :
AbstractChainedExpressionWrapper<NameSyntax, BaseArgumentListSyntax>
{
public CSharpChainedExpressionWrapper()
: base(CSharpIndentationService.Instance, CSharpSyntaxFacts.Instance)
{
}
protected override SyntaxTriviaList GetNewLineBeforeOperatorTrivia(SyntaxTriviaList newLine)
=> newLine;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Indentation;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Wrapping.ChainedExpression;
namespace Microsoft.CodeAnalysis.CSharp.Wrapping.ChainedExpression
{
internal class CSharpChainedExpressionWrapper :
AbstractChainedExpressionWrapper<NameSyntax, BaseArgumentListSyntax>
{
public CSharpChainedExpressionWrapper()
: base(CSharpIndentationService.Instance, CSharpSyntaxFacts.Instance)
{
}
protected override SyntaxTriviaList GetNewLineBeforeOperatorTrivia(SyntaxTriviaList newLine)
=> newLine;
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/Remote/Core/ExternalAccess/Pythia/Api/PythiaPinnedSolutionInfoWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
[DataContract]
internal readonly struct PythiaPinnedSolutionInfoWrapper
{
[DataMember(Order = 0)]
internal readonly PinnedSolutionInfo UnderlyingObject;
public PythiaPinnedSolutionInfoWrapper(PinnedSolutionInfo underlyingObject)
=> UnderlyingObject = underlyingObject;
public static implicit operator PythiaPinnedSolutionInfoWrapper(PinnedSolutionInfo info)
=> new(info);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
[DataContract]
internal readonly struct PythiaPinnedSolutionInfoWrapper
{
[DataMember(Order = 0)]
internal readonly PinnedSolutionInfo UnderlyingObject;
public PythiaPinnedSolutionInfoWrapper(PinnedSolutionInfo underlyingObject)
=> UnderlyingObject = underlyingObject;
public static implicit operator PythiaPinnedSolutionInfoWrapper(PinnedSolutionInfo info)
=> new(info);
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/EditorFeatures/TestUtilities/Classification/FormattedClassifications.RegexTypes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Classification;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification
{
public static partial class FormattedClassifications
{
public static class Regex
{
[DebuggerStepThrough]
public static FormattedClassification Anchor(string value) => New(value, ClassificationTypeNames.RegexAnchor);
[DebuggerStepThrough]
public static FormattedClassification Grouping(string value) => New(value, ClassificationTypeNames.RegexGrouping);
[DebuggerStepThrough]
public static FormattedClassification OtherEscape(string value) => New(value, ClassificationTypeNames.RegexOtherEscape);
[DebuggerStepThrough]
public static FormattedClassification SelfEscapedCharacter(string value) => New(value, ClassificationTypeNames.RegexSelfEscapedCharacter);
[DebuggerStepThrough]
public static FormattedClassification Alternation(string value) => New(value, ClassificationTypeNames.RegexAlternation);
[DebuggerStepThrough]
public static FormattedClassification CharacterClass(string value) => New(value, ClassificationTypeNames.RegexCharacterClass);
[DebuggerStepThrough]
public static FormattedClassification Text(string value) => New(value, ClassificationTypeNames.RegexText);
[DebuggerStepThrough]
public static FormattedClassification Quantifier(string value) => New(value, ClassificationTypeNames.RegexQuantifier);
[DebuggerStepThrough]
public static FormattedClassification Comment(string value) => New(value, ClassificationTypeNames.RegexComment);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Classification;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification
{
public static partial class FormattedClassifications
{
public static class Regex
{
[DebuggerStepThrough]
public static FormattedClassification Anchor(string value) => New(value, ClassificationTypeNames.RegexAnchor);
[DebuggerStepThrough]
public static FormattedClassification Grouping(string value) => New(value, ClassificationTypeNames.RegexGrouping);
[DebuggerStepThrough]
public static FormattedClassification OtherEscape(string value) => New(value, ClassificationTypeNames.RegexOtherEscape);
[DebuggerStepThrough]
public static FormattedClassification SelfEscapedCharacter(string value) => New(value, ClassificationTypeNames.RegexSelfEscapedCharacter);
[DebuggerStepThrough]
public static FormattedClassification Alternation(string value) => New(value, ClassificationTypeNames.RegexAlternation);
[DebuggerStepThrough]
public static FormattedClassification CharacterClass(string value) => New(value, ClassificationTypeNames.RegexCharacterClass);
[DebuggerStepThrough]
public static FormattedClassification Text(string value) => New(value, ClassificationTypeNames.RegexText);
[DebuggerStepThrough]
public static FormattedClassification Quantifier(string value) => New(value, ClassificationTypeNames.RegexQuantifier);
[DebuggerStepThrough]
public static FormattedClassification Comment(string value) => New(value, ClassificationTypeNames.RegexComment);
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Xunit;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class SyntaxBinderTests : CompilingTestBase
{
[Fact, WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
public void EnumBinaryOps()
{
string source = @"
[Flags]
internal enum TestEnum
{
None,
Tags,
FilePath,
Capabilities,
Visibility,
AllProperties = FilePath | Visibility
}
class C {
public void Goo(){
var x = TestEnum.FilePath | TestEnum.Visibility;
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var orNodes = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().ToArray();
Assert.Equal(2, orNodes.Length);
var insideEnumDefinition = semanticModel.GetSymbolInfo(orNodes[0]);
var insideMethodBody = semanticModel.GetSymbolInfo(orNodes[1]);
Assert.False(insideEnumDefinition.IsEmpty);
Assert.False(insideMethodBody.IsEmpty);
Assert.NotEqual(insideEnumDefinition, insideMethodBody);
Assert.Equal("System.Int32 System.Int32.op_BitwiseOr(System.Int32 left, System.Int32 right)", insideEnumDefinition.Symbol.ToTestDisplayString());
Assert.Equal("TestEnum TestEnum.op_BitwiseOr(TestEnum left, TestEnum right)", insideMethodBody.Symbol.ToTestDisplayString());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void EnumBinaryOps_IOperation()
{
string source = @"
using System;
[Flags]
internal enum TestEnum
{
None,
Tags,
FilePath,
Capabilities,
Visibility,
AllProperties = FilePath | Visibility
}
class C
{
public void Goo()
{
var x = /*<bind>*/TestEnum.FilePath | TestEnum.Visibility/*</bind>*/;
Console.Write(x);
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: TestEnum, Constant: 6) (Syntax: 'TestEnum.Fi ... .Visibility')
Left:
IFieldReferenceOperation: TestEnum.FilePath (Static) (OperationKind.FieldReference, Type: TestEnum, Constant: 2) (Syntax: 'TestEnum.FilePath')
Instance Receiver:
null
Right:
IFieldReferenceOperation: TestEnum.Visibility (Static) (OperationKind.FieldReference, Type: TestEnum, Constant: 4) (Syntax: 'TestEnum.Visibility')
Instance Receiver:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(543895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543895")]
public void TestBug11947()
{
// Due to a long-standing bug, the native compiler allows underlying-enum with the same
// semantics as enum-underlying. (That is, the math is done in the underlying type and
// then cast back to the enum type.)
string source = @"
using System;
public enum E { Zero, One, Two };
class Test
{
static void Main()
{
E e = E.One;
int x = 3;
E r = x - e;
Console.Write(r);
E? en = E.Two;
int? xn = 2;
E? rn = xn - en;
Console.Write(rn);
}
}";
CompileAndVerify(source: source, expectedOutput: "TwoZero");
}
private const string StructWithUserDefinedBooleanOperators = @"
struct S
{
private int num;
private string str;
public S(int num, char chr)
{
this.num = num;
this.str = chr.ToString();
}
public S(int num, string str)
{
this.num = num;
this.str = str;
}
public static S operator & (S x, S y)
{
return new S(x.num & y.num, '(' + x.str + '&' + y.str + ')');
}
public static S operator | (S x, S y)
{
return new S(x.num | y.num, '(' + x.str + '|' + y.str + ')');
}
public static bool operator true(S s)
{
return s.num != 0;
}
public static bool operator false(S s)
{
return s.num == 0;
}
public override string ToString()
{
return this.num.ToString() + ':' + this.str;
}
}
";
[Fact]
public void TestUserDefinedLogicalOperators()
{
string source = @"
using System;
class C
{
static void Main()
{
S f = new S(0, 'f');
S t = new S(1, 't');
Console.WriteLine((f && f) && f);
Console.WriteLine((f && f) && t);
Console.WriteLine((f && t) && f);
Console.WriteLine((f && t) && t);
Console.WriteLine((t && f) && f);
Console.WriteLine((t && f) && t);
Console.WriteLine((t && t) && f);
Console.WriteLine((t && t) && t);
Console.WriteLine('-');
Console.WriteLine((f && f) || f);
Console.WriteLine((f && f) || t);
Console.WriteLine((f && t) || f);
Console.WriteLine((f && t) || t);
Console.WriteLine((t && f) || f);
Console.WriteLine((t && f) || t);
Console.WriteLine((t && t) || f);
Console.WriteLine((t && t) || t);
Console.WriteLine('-');
Console.WriteLine((f || f) && f);
Console.WriteLine((f || f) && t);
Console.WriteLine((f || t) && f);
Console.WriteLine((f || t) && t);
Console.WriteLine((t || f) && f);
Console.WriteLine((t || f) && t);
Console.WriteLine((t || t) && f);
Console.WriteLine((t || t) && t);
Console.WriteLine('-');
Console.WriteLine((f || f) || f);
Console.WriteLine((f || f) || t);
Console.WriteLine((f || t) || f);
Console.WriteLine((f || t) || t);
Console.WriteLine((t || f) || f);
Console.WriteLine((t || f) || t);
Console.WriteLine((t || t) || f);
Console.WriteLine((t || t) || t);
Console.WriteLine('-');
Console.WriteLine(f && (f && f));
Console.WriteLine(f && (f && t));
Console.WriteLine(f && (t && f));
Console.WriteLine(f && (t && t));
Console.WriteLine(t && (f && f));
Console.WriteLine(t && (f && t));
Console.WriteLine(t && (t && f));
Console.WriteLine(t && (t && t));
Console.WriteLine('-');
Console.WriteLine(f && (f || f));
Console.WriteLine(f && (f || t));
Console.WriteLine(f && (t || f));
Console.WriteLine(f && (t || t));
Console.WriteLine(t && (f || f));
Console.WriteLine(t && (f || t));
Console.WriteLine(t && (t || f));
Console.WriteLine(t && (t || t));
Console.WriteLine('-');
Console.WriteLine(f || (f && f));
Console.WriteLine(f || (f && t));
Console.WriteLine(f || (t && f));
Console.WriteLine(f || (t && t));
Console.WriteLine(t || (f && f));
Console.WriteLine(t || (f && t));
Console.WriteLine(t || (t && f));
Console.WriteLine(t || (t && t));
Console.WriteLine('-');
Console.WriteLine(f || (f || f));
Console.WriteLine(f || (f || t));
Console.WriteLine(f || (t || f));
Console.WriteLine(f || (t || t));
Console.WriteLine(t || (f || f));
Console.WriteLine(t || (f || t));
Console.WriteLine(t || (t || f));
Console.WriteLine(t || (t || t));
}
}
" + StructWithUserDefinedBooleanOperators;
string output = @"0:f
0:f
0:f
0:f
0:(t&f)
0:(t&f)
0:((t&t)&f)
1:((t&t)&t)
-
0:(f|f)
1:(f|t)
0:(f|f)
1:(f|t)
0:((t&f)|f)
1:((t&f)|t)
1:(t&t)
1:(t&t)
-
0:(f|f)
0:(f|f)
0:((f|t)&f)
1:((f|t)&t)
0:(t&f)
1:(t&t)
0:(t&f)
1:(t&t)
-
0:((f|f)|f)
1:((f|f)|t)
1:(f|t)
1:(f|t)
1:t
1:t
1:t
1:t
-
0:f
0:f
0:f
0:f
0:(t&f)
0:(t&f)
0:(t&(t&f))
1:(t&(t&t))
-
0:f
0:f
0:f
0:f
0:(t&(f|f))
1:(t&(f|t))
1:(t&t)
1:(t&t)
-
0:(f|f)
0:(f|f)
0:(f|(t&f))
1:(f|(t&t))
1:t
1:t
1:t
1:t
-
0:(f|(f|f))
1:(f|(f|t))
1:(f|t)
1:(f|t)
1:t
1:t
1:t
1:t";
CompileAndVerify(source: source, expectedOutput: output);
}
[Fact]
public void TestUserDefinedLogicalOperators2()
{
string source = @"
using System;
class C
{
static void Main()
{
S f = new S(0, 'f');
S t = new S(1, 't');
Console.Write((f && f) && f ? 1 : 0);
Console.Write((f && f) && t ? 1 : 0);
Console.Write((f && t) && f ? 1 : 0);
Console.Write((f && t) && t ? 1 : 0);
Console.Write((t && f) && f ? 1 : 0);
Console.Write((t && f) && t ? 1 : 0);
Console.Write((t && t) && f ? 1 : 0);
Console.Write((t && t) && t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f && f) || f ? 1 : 0);
Console.Write((f && f) || t ? 1 : 0);
Console.Write((f && t) || f ? 1 : 0);
Console.Write((f && t) || t ? 1 : 0);
Console.Write((t && f) || f ? 1 : 0);
Console.Write((t && f) || t ? 1 : 0);
Console.Write((t && t) || f ? 1 : 0);
Console.Write((t && t) || t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f || f) && f ? 1 : 0);
Console.Write((f || f) && t ? 1 : 0);
Console.Write((f || t) && f ? 1 : 0);
Console.Write((f || t) && t ? 1 : 0);
Console.Write((t || f) && f ? 1 : 0);
Console.Write((t || f) && t ? 1 : 0);
Console.Write((t || t) && f ? 1 : 0);
Console.Write((t || t) && t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f || f) || f ? 1 : 0);
Console.Write((f || f) || t ? 1 : 0);
Console.Write((f || t) || f ? 1 : 0);
Console.Write((f || t) || t ? 1 : 0);
Console.Write((t || f) || f ? 1 : 0);
Console.Write((t || f) || t ? 1 : 0);
Console.Write((t || t) || f ? 1 : 0);
Console.Write((t || t) || t ? 1 : 0);
Console.WriteLine('-');
Console.Write(f && (f && f) ? 1 : 0);
Console.Write(f && (f && t) ? 1 : 0);
Console.Write(f && (t && f) ? 1 : 0);
Console.Write(f && (t && t) ? 1 : 0);
Console.Write(t && (f && f) ? 1 : 0);
Console.Write(t && (f && t) ? 1 : 0);
Console.Write(t && (t && f) ? 1 : 0);
Console.Write(t && (t && t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f && (f || f) ? 1 : 0);
Console.Write(f && (f || t) ? 1 : 0);
Console.Write(f && (t || f) ? 1 : 0);
Console.Write(f && (t || t) ? 1 : 0);
Console.Write(t && (f || f) ? 1 : 0);
Console.Write(t && (f || t) ? 1 : 0);
Console.Write(t && (t || f) ? 1 : 0);
Console.Write(t && (t || t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f || (f && f) ? 1 : 0);
Console.Write(f || (f && t) ? 1 : 0);
Console.Write(f || (t && f) ? 1 : 0);
Console.Write(f || (t && t) ? 1 : 0);
Console.Write(t || (f && f) ? 1 : 0);
Console.Write(t || (f && t) ? 1 : 0);
Console.Write(t || (t && f) ? 1 : 0);
Console.Write(t || (t && t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f || (f || f) ? 1 : 0);
Console.Write(f || (f || t) ? 1 : 0);
Console.Write(f || (t || f) ? 1 : 0);
Console.Write(f || (t || t) ? 1 : 0);
Console.Write(t || (f || f) ? 1 : 0);
Console.Write(t || (f || t) ? 1 : 0);
Console.Write(t || (t || f) ? 1 : 0);
Console.Write(t || (t || t) ? 1 : 0);
}
}
" + StructWithUserDefinedBooleanOperators;
string output = @"
00000001-
01010111-
00010101-
01111111-
00000001-
00000111-
00011111-
01111111";
CompileAndVerify(source: source, expectedOutput: output);
}
[Fact]
public void TestOperatorTrue()
{
string source = @"
using System;
struct S
{
private int x;
public S(int x) { this.x = x; }
public static bool operator true(S s) { return s.x != 0; }
public static bool operator false(S s) { return s.x == 0; }
}
class C
{
static void Main()
{
S zero = new S(0);
S one = new S(1);
if (zero)
Console.Write('a');
else
Console.Write('b');
if (one)
Console.Write('c');
else
Console.Write('d');
Console.Write( zero ? 'e' : 'f' );
Console.Write( one ? 'g' : 'h' );
while(zero)
{
Console.Write('i');
}
while(one)
{
Console.Write('j');
break;
}
do
{
Console.Write('k');
}
while(zero);
bool first = true;
do
{
Console.Write('l');
if (!first) break;
first = false;
}
while(one);
for( ; zero ; )
{
Console.Write('m');
}
for( ; one ; )
{
Console.Write('n');
break;
}
}
}";
string output = @"bcfgjklln";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestOperatorTrue_IOperation()
{
string source = @"
using System;
struct S
{
private int x;
public S(int x) { this.x = x; }
public static bool operator true(S s) { return s.x != 0; }
public static bool operator false(S s) { return s.x == 0; }
}
class C
{
static void Main(S zero, S one)
/*<bind>*/{
if (zero)
Console.Write('a');
else
Console.Write('b');
Console.Write(one ? 'g' : 'h');
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (zero) ... Write('b');')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S s)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'zero')
Operand:
IParameterReferenceOperation: zero (OperationKind.ParameterReference, Type: S) (Syntax: 'zero')
WhenTrue:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write('a');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write('a')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: ''a'')
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
WhenFalse:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write('b');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write('b')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: ''b'')
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: b) (Syntax: ''b'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... 'g' : 'h');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... 'g' : 'h')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'one ? 'g' : 'h'')
IConditionalOperation (OperationKind.Conditional, Type: System.Char) (Syntax: 'one ? 'g' : 'h'')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S s)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'one')
Operand:
IParameterReferenceOperation: one (OperationKind.ParameterReference, Type: S) (Syntax: 'one')
WhenTrue:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: g) (Syntax: ''g'')
WhenFalse:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: h) (Syntax: ''h'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUnaryOperatorOverloading()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator - (S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~ (S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator ! (S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
Console.Write( + ~ ! - a );
Console.Write( a );
Console.Write( a++ );
Console.Write( a );
Console.Write( b );
Console.Write( ++b );
Console.Write( b );
Console.Write( c );
Console.Write( c-- );
Console.Write( c );
Console.Write( d );
Console.Write( --d );
Console.Write( d );
}
}";
string output = "(+(~(!(-a))))aa(a+1)b(b+1)(b+1)cc(c-1)d(d-1)(d-1)";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUnaryOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
Console.Write(+a);
Console.Write(-a);
Console.Write(~a);
Console.Write(!a);
Console.Write(+~!-a);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (5 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(+a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(+a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '+a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '+a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: S S.op_UnaryPlus(S x)) (OperationKind.Unary, Type: S) (Syntax: '+a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(-a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(-a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '-a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '-a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: S S.op_UnaryNegation(S x)) (OperationKind.Unary, Type: S) (Syntax: '-a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(~a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(~a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '~a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '~a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: S S.op_OnesComplement(S x)) (OperationKind.Unary, Type: S) (Syntax: '~a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(!a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(!a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '!a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '!a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: S S.op_LogicalNot(S x)) (OperationKind.Unary, Type: S) (Syntax: '!a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(+~!-a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(+~!-a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '+~!-a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '+~!-a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: S S.op_UnaryPlus(S x)) (OperationKind.Unary, Type: S) (Syntax: '+~!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: S S.op_OnesComplement(S x)) (OperationKind.Unary, Type: S) (Syntax: '~!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: S S.op_LogicalNot(S x)) (OperationKind.Unary, Type: S) (Syntax: '!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: S S.op_UnaryNegation(S x)) (OperationKind.Unary, Type: S) (Syntax: '-a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '++a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a++')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '--a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a--')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperatorOverloading_Checked_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
checked
{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '++a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a++')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '--a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a--')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperator_IOperation()
{
string source = @"
using System;
class C
{
static void Method(int a)
/*<bind>*/{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IIncrementOrDecrementOperation (Postfix) (OperationKind.Decrement, Type: System.Int32) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperator_Checked_IOperation()
{
string source = @"
using System;
class C
{
static void Method(int a)
/*<bind>*/{
checked
{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IIncrementOrDecrementOperation (Prefix, Checked) (OperationKind.Increment, Type: System.Int32) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IIncrementOrDecrementOperation (Postfix, Checked) (OperationKind.Increment, Type: System.Int32) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IIncrementOrDecrementOperation (Prefix, Checked) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IIncrementOrDecrementOperation (Postfix, Checked) (OperationKind.Decrement, Type: System.Int32) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestBinaryOperatorOverloading()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public static S operator == (S x, S y) { return new S('(' + x.str + '=' + '=' + y.str + ')'); }
public static S operator != (S x, S y) { return new S('(' + x.str + '!' + '=' + y.str + ')'); }
public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); }
public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); }
public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); }
public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
S j = new S('j');
S k = new S('k');
S l = new S('l');
S m = new S('m');
S n = new S('n');
S o = new S('o');
S p = new S('p');
Console.WriteLine(
(a >> 10) + (b << 20) - c * d / e % f & g |
h ^ i == j != k < l > m <= o >= p);
}
}";
string output = @"(((((a>>10)+(b<<20))-(((c*d)/e)%f))&g)|(h^((i==j)!=((((k<l)>m)<=o)>=p))))";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestBinaryOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public static S operator ==(S x, S y) { return new S('(' + x.str + '=' + '=' + y.str + ')'); }
public static S operator !=(S x, S y) { return new S('(' + x.str + '!' + '=' + y.str + ')'); }
public static S operator >=(S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); }
public static S operator <=(S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); }
public static S operator >(S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); }
public static S operator <(S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
S j = new S('j');
S k = new S('k');
S l = new S('l');
S m = new S('m');
S n = new S('n');
S o = new S('o');
S p = new S('p');
Console.WriteLine(
/*<bind>*/(a >> 10) + (b << 20) - c * d / e % f & g |
h ^ i == j != k < l > m <= o >= p/*</bind>*/);
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... / e % f & g')
Left:
IBinaryOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... * d / e % f')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + (b << 20)')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.Binary, Type: S) (Syntax: 'a >> 10')
Left:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IBinaryOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.Binary, Type: S) (Syntax: 'b << 20')
Left:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: S) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
Right:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d / e % f')
Left:
IBinaryOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d / e')
Left:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: S) (Syntax: 'c')
Right:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: S) (Syntax: 'd')
Right:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: S) (Syntax: 'e')
Right:
ILocalReferenceOperation: f (OperationKind.LocalReference, Type: S) (Syntax: 'f')
Right:
ILocalReferenceOperation: g (OperationKind.LocalReference, Type: S) (Syntax: 'g')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'h ^ i == j ... m <= o >= p')
Left:
ILocalReferenceOperation: h (OperationKind.LocalReference, Type: S) (Syntax: 'h')
Right:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperatorMethod: S S.op_Inequality(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'i == j != k ... m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: S S.op_Equality(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'i == j')
Left:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: S) (Syntax: 'i')
Right:
ILocalReferenceOperation: j (OperationKind.LocalReference, Type: S) (Syntax: 'j')
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperatorMethod: S S.op_GreaterThanOrEqual(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperatorMethod: S S.op_LessThanOrEqual(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m <= o')
Left:
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperatorMethod: S S.op_GreaterThan(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m')
Left:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperatorMethod: S S.op_LessThan(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l')
Left:
ILocalReferenceOperation: k (OperationKind.LocalReference, Type: S) (Syntax: 'k')
Right:
ILocalReferenceOperation: l (OperationKind.LocalReference, Type: S) (Syntax: 'l')
Right:
ILocalReferenceOperation: m (OperationKind.LocalReference, Type: S) (Syntax: 'm')
Right:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: S) (Syntax: 'o')
Right:
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: S) (Syntax: 'p')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0660: 'S' defines operator == or operator != but does not override Object.Equals(object o)
// struct S
Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "S").WithArguments("S").WithLocation(3, 8),
// CS0661: 'S' defines operator == or operator != but does not override Object.GetHashCode()
// struct S
Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "S").WithArguments("S").WithLocation(3, 8)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(657084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657084")]
[CompilerTrait(CompilerFeature.IOperation)]
public void DuplicateOperatorInSubclass()
{
string source = @"
class B
{
public static B operator +(C c, B b) { return null; }
}
class C : B
{
public static B operator +(C c, B b) { return null; }
}
class Test
{
public static void Main()
{
B b = /*<bind>*/new C() + new B()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'new C() + new B()')
Left:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Right:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0034: Operator '+' is ambiguous on operands of type 'C' and 'B'
// B b = /*<bind>*/new C() + new B()/*</bind>*/;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "new C() + new B()").WithArguments("+", "C", "B").WithLocation(16, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Enums_Dynamic_Unambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
using System.Collections.Generic;
class C<T>
{
enum E { A }
public void M()
{
var eq1 = C<dynamic>.E.A == C<object>.E.A;
var eq2 = C<object>.E.A == C<dynamic>.E.A;
var eq3 = C<Dictionary<object, dynamic>>.E.A == C<Dictionary<dynamic, object>>.E.A;
var neq1 = C<dynamic>.E.A != C<object>.E.A;
var neq2 = C<object>.E.A != C<dynamic>.E.A;
var neq3 = C<Dictionary<object, dynamic>>.E.A != C<Dictionary<dynamic, object>>.E.A;
var lt1 = C<dynamic>.E.A < C<object>.E.A;
var lt2 = C<object>.E.A < C<dynamic>.E.A;
var lt3 = C<Dictionary<object, dynamic>>.E.A < C<Dictionary<dynamic, object>>.E.A;
var lte1 = C<dynamic>.E.A <= C<object>.E.A;
var lte2 = C<object>.E.A <= C<dynamic>.E.A;
var lte3 = C<Dictionary<object, dynamic>>.E.A <= C<Dictionary<dynamic, object>>.E.A;
var gt1 = C<dynamic>.E.A > C<object>.E.A;
var gt2 = C<object>.E.A > C<dynamic>.E.A;
var gt3 = C<Dictionary<object, dynamic>>.E.A > C<Dictionary<dynamic, object>>.E.A;
var gte1 = C<dynamic>.E.A >= C<object>.E.A;
var gte2 = C<object>.E.A >= C<dynamic>.E.A;
var gte3 = C<Dictionary<object, dynamic>>.E.A >= C<Dictionary<dynamic, object>>.E.A;
var sub1 = C<dynamic>.E.A - C<object>.E.A;
var sub2 = C<object>.E.A - C<dynamic>.E.A;
var sub3 = C<Dictionary<object, dynamic>>.E.A - C<Dictionary<dynamic, object>>.E.A;
var subu1 = C<dynamic>.E.A - 1;
var subu3 = C<Dictionary<object, dynamic>>.E.A - 1;
var usub1 = 1 - C<dynamic>.E.A;
var usub3 = 1 - C<Dictionary<object, dynamic>>.E.A;
var addu1 = C<dynamic>.E.A + 1;
var addu3 = C<Dictionary<object, dynamic>>.E.A + 1;
var uadd1 = 1 + C<dynamic>.E.A;
var uadd3 = 1 + C<Dictionary<object, dynamic>>.E.A;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics();
}
[Fact, WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
[CompilerTrait(CompilerFeature.IOperation)]
public void TestBinaryOperatorOverloading_Enums_Dynamic_Ambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
enum E { A }
public void M()
{
var and = C<dynamic>.E.A & C<object>.E.A;
var or = C<dynamic>.E.A | C<object>.E.A;
var xor = C<dynamic>.E.A ^ C<object>.E.A;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (10,19): error CS0034: Operator '&' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A & C<object>.E.A").WithArguments("&", "C<dynamic>.E", "C<object>.E"),
// (11,18): error CS0034: Operator '|' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A | C<object>.E.A").WithArguments("|", "C<dynamic>.E", "C<object>.E"),
// (12,19): error CS0034: Operator '^' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A ^ C<object>.E.A").WithArguments("^", "C<dynamic>.E", "C<object>.E"));
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Unambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
delegate void A<U, V>(U u, V v);
C<dynamic>.A<object, object> d1 = null;
C<object>.A<object, object> d2 = null;
C<dynamic>.A<object, dynamic> d3 = null;
C<object>.A<dynamic, object> d4 = null;
public void M()
{
var eq1 = d1 == d2;
var eq2 = d1 == d3;
var eq3 = d1 == d4;
var eq4 = d2 == d3;
var neq1 = d1 != d2;
var neq2 = d1 != d3;
var neq3 = d1 != d4;
var neq4 = d2 != d3;
}
}
";
// Dev11 reports error CS0034: Operator '...' is ambiguous on operands ... and ... for all combinations
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics();
}
[Fact]
public void TestBinaryOperatorOverloading_UserDefined_Dynamic_Unambiguous()
{
string source = @"
class D<T>
{
public class C
{
public static int operator +(C x, C y) { return 1; }
}
}
class X
{
static void Main()
{
var x = new D<object>.C();
var y = new D<dynamic>.C();
var z = /*<bind>*/x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 D<System.Object>.C.op_Addition(D<System.Object>.C x, D<System.Object>.C y)) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: D<System.Object>.C) (Syntax: 'x')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: D<System.Object>.C, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: D<dynamic>.C) (Syntax: 'y')
";
// Dev11 reports error CS0121: The call is ambiguous between the following methods or properties:
// 'D<object>.C.operator+(D<object>.C, D<object>.C)' and 'D<dynamic>.C.operator +(D<dynamic>.C, D<dynamic>.C)'
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void TestBinaryOperatorOverloading_UserDefined_Dynamic_Ambiguous()
{
string source = @"
class D<T>
{
public class C
{
public static C operator +(C x, C y) { return null; }
}
}
class X
{
static void Main()
{
var x = new D<object>.C();
var y = new D<dynamic>.C();
var z = /*<bind>*/x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: D<System.Object>.C, IsInvalid) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: D<dynamic>.C, IsInvalid) (Syntax: 'y')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0034: Operator '+' is ambiguous on operands of type 'D<object>.C' and 'D<dynamic>.C'
// var z = /*<bind>*/x + y/*</bind>*/;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "D<object>.C", "D<dynamic>.C").WithLocation(16, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Ambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
delegate void A<U, V>(U u, V v);
C<dynamic>.A<object, object> d1 = null;
C<object>.A<object, object> d2 = null;
C<dynamic>.A<object, dynamic> d3 = null;
C<object>.A<dynamic, object> d4 = null;
public void M()
{
var add1 = d1 + d2;
var add2 = d1 + d3;
var add3 = d1 + d4;
var add4 = d2 + d3;
var sub1 = d1 - d2;
var sub2 = d1 - d3;
var sub3 = d1 - d4;
var sub4 = d2 - d3;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (17,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<object, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d2").WithArguments("+", "C<dynamic>.A<object, object>", "C<object>.A<object, object>"),
// (18,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d3").WithArguments("+", "C<dynamic>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (19,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<dynamic, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d4").WithArguments("+", "C<dynamic>.A<object, object>", "C<object>.A<dynamic, object>"),
// (20,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<object>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d2 + d3").WithArguments("+", "C<object>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (22,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<object, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d2").WithArguments("-", "C<dynamic>.A<object, object>", "C<object>.A<object, object>"),
// (23,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d3").WithArguments("-", "C<dynamic>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (24,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<dynamic, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d4").WithArguments("-", "C<dynamic>.A<object, object>", "C<object>.A<dynamic, object>"),
// (25,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<object>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d2 - d3").WithArguments("-", "C<object>.A<object, object>", "C<dynamic>.A<object, dynamic>"));
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Ambiguous_Inference()
{
string source = @"
using System;
class Program
{
static void Main()
{
Action<object> a = null;
Goo(c => c == a);
}
static void Goo(Func<Action<object>, IComparable> x) { }
static void Goo(Func<Action<dynamic>, IConvertible> x) { }
}
";
// Dev11 considers Action<object> == Action<dynamic> ambiguous and thus chooses Goo(Func<Action<object>, IComparable>) overload.
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Goo(System.Func<System.Action<object>, System.IComparable>)' and 'Program.Goo(System.Func<System.Action<dynamic>, System.IConvertible>)'
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("Program.Goo(System.Func<System.Action<object>, System.IComparable>)", "Program.Goo(System.Func<System.Action<dynamic>, System.IConvertible>)"));
}
[Fact]
public void TestBinaryOperatorOverloading_Pointers_Dynamic()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
using System.Collections.Generic;
unsafe class C<T>
{
enum E { A }
public void M()
{
var o = C<object>.E.A;
var d = C<dynamic>.E.A;
var dict1 = C<Dictionary<object, dynamic>>.E.A;
var dict2 = C<Dictionary<dynamic, object>>.E.A;
var eq1 = &o == &d;
var eq2 = &d == &o;
var eq3 = &dict1 == &dict2;
var eq4 = &dict2 == &dict1;
var neq1 = &o != &d;
var neq2 = &d != &o;
var neq3 = &dict1 != &dict2;
var neq4 = &dict2 != &dict1;
var sub1 = &o - &d;
var sub2 = &d - &o;
var sub3 = &dict1 - &dict2;
var sub4 = &dict2 - &dict1;
var subi1 = &o - 1;
var subi2 = &d - 1;
var subi3 = &dict1 - 1;
var subi4 = &dict2 - 1;
var addi1 = &o + 1;
var addi2 = &d + 1;
var addi3 = &dict1 + 1;
var addi4 = &dict2 + 1;
var iadd1 = 1 + &o;
var iadd2 = 1 + &d;
var iadd3 = 1 + &dict1;
var iadd4 = 1 + &dict2;
}
}
";
// Dev11 reports "error CS0034: Operator '-' is ambiguous on operands ... and ..." for all ptr - ptr
CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void TestOverloadResolutionTiebreakers()
{
string source = @"
using System;
struct S
{
public static bool operator == (S x, S y) { return true; }
public static bool operator != (S x, S y) { return false; }
public static bool operator == (S? x, S? y) { return true; }
public static bool operator != (S? x, S? y) { return false; }
public override bool Equals(object s) { return true; }
public override int GetHashCode() { return 0; }
public override string ToString() { return this.str; }
}
class X<T>
{
public static int operator +(X<T> x, int y) { return 0; }
public static int operator +(X<T> x, T y) { return 0; }
}
struct Q<U> where U : struct
{
public static int operator +(Q<U> x, int y) { return 0; }
public static int? operator +(Q<U>? x, U? y) { return 1; }
}
class C
{
static void M()
{
S s1 = new S();
S s2 = new S();
S? s3 = new S();
S? s4 = null;
X<int> xint = null;
int x = xint + 123; //-UserDefinedAddition
// In this case the native compiler and the spec disagree. Roslyn implements the spec.
// The tiebreaker is supposed to check for *specificity* first, and then *liftedness*.
// The native compiler eliminates the lifted operator even if it is more specific:
int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
// All of these go to a user-defined equality operator;
// the lifted form is always worse than the unlifted form,
// and the user-defined form is always better than turning
// '== null' into a call to HasValue().
bool[] b =
{
s1 == s2, //-UserDefinedEqual
s1 == s3, //-UserDefinedEqual
s1 == null, //-UserDefinedEqual
s3 == s1, //-UserDefinedEqual
s3 == s4, //-UserDefinedEqual
s3 == null, //-UserDefinedEqual
null == s1, //-UserDefinedEqual
null == s3 //-UserDefinedEqual
};
}
}";
TestOperatorKinds(source);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestOverloadResolutionTiebreakers_IOperation()
{
string source = @"
using System;
struct S
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return false; }
public static bool operator ==(S? x, S? y) { return true; }
public static bool operator !=(S? x, S? y) { return false; }
public override bool Equals(object s) { return true; }
public override int GetHashCode() { return 0; }
public override string ToString() { return this.str; }
}
class X<T>
{
public static int operator +(X<T> x, int y) { return 0; }
public static int operator +(X<T> x, T y) { return 0; }
}
struct Q<U> where U : struct
{
public static int operator +(Q<U> x, int y) { return 0; }
public static int? operator +(Q<U>? x, U? y) { return 1; }
}
class C
{
static void M(S s1, S s2, S? s3, S? s4, X<int> xint)
/*<bind>*/{
int x = xint + 123; //-UserDefinedAddition
// In this case the native compiler and the spec disagree. Roslyn implements the spec.
// The tiebreaker is supposed to check for *specificity* first, and then *liftedness*.
// The native compiler eliminates the lifted operator even if it is more specific:
int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
// All of these go to a user-defined equality operator;
// the lifted form is always worse than the unlifted form,
// and the user-defined form is always better than turning
// '== null' into a call to HasValue().
bool[] b =
{
s1 == s2, //-UserDefinedEqual
s1 == s3, //-UserDefinedEqual
s1 == null, //-UserDefinedEqual
s3 == s1, //-UserDefinedEqual
s3 == s4, //-UserDefinedEqual
s3 == null, //-UserDefinedEqual
null == s1, //-UserDefinedEqual
null == s3 //-UserDefinedEqual
};
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 x
Local_2: System.Int32? q
Local_3: System.Boolean[] b
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int x = xint + 123;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int x = xint + 123')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = xint + 123')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= xint + 123')
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 X<System.Int32>.op_Addition(X<System.Int32> x, System.Int32 y)) (OperationKind.Binary, Type: System.Int32) (Syntax: 'xint + 123')
Left:
IParameterReferenceOperation: xint (OperationKind.ParameterReference, Type: X<System.Int32>) (Syntax: 'xint')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123')
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int? q = ne ... new int?();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int? q = ne ... new int?()')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32? q) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'q = new Q<i ... new int?()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Q<int ... new int?()')
IBinaryOperation (BinaryOperatorKind.Add, IsLifted) (OperatorMethod: System.Int32 Q<System.Int32>.op_Addition(Q<System.Int32> x, System.Int32 y)) (OperationKind.Binary, Type: System.Int32?) (Syntax: 'new Q<int>? ... new int?()')
Left:
IObjectCreationOperation (Constructor: Q<System.Int32>?..ctor()) (OperationKind.ObjectCreation, Type: Q<System.Int32>?) (Syntax: 'new Q<int>?()')
Arguments(0)
Initializer:
null
Right:
IObjectCreationOperation (Constructor: System.Int32?..ctor()) (OperationKind.ObjectCreation, Type: System.Int32?) (Syntax: 'new int?()')
Arguments(0)
Initializer:
null
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'bool[] b = ... };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'bool[] b = ... }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Boolean[] b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = ... }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Boolean[], IsImplicit) (Syntax: '{ ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 8, IsImplicit) (Syntax: '{ ... }')
Initializer:
IArrayInitializerOperation (8 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ ... }')
Element Values(8):
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S x, S y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == s2')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S) (Syntax: 's2')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == s3')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == null')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == s1')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == s4')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IParameterReferenceOperation: s4 (OperationKind.ParameterReference, Type: S?) (Syntax: 's4')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == null')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'null == s1')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'null == s3')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0458: The result of the expression is always 'null' of type 'int?'
// int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
Diagnostic(ErrorCode.WRN_AlwaysNull, "new Q<int>?() + new int?()").WithArguments("int?").WithLocation(37, 18),
// CS1061: 'S' does not contain a definition for 'str' and no extension method 'str' accepting a first argument of type 'S' could be found (are you missing a using directive or an assembly reference?)
// public override string ToString() { return this.str; }
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "str").WithArguments("S", "str").WithLocation(11, 53)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUserDefinedCompoundAssignment()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
Console.WriteLine(a);
}
}";
string output = @"((((((((((a+b)-c)*d)/e)%f)<<10)>>20)&g)|h)^i)";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedCompoundAssignment_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main(S a, S b, S c, S d, S e, S f, S g, S h, S i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: S) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: S) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: S) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: S) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: S) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: S) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: S) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: S) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedCompoundAssignment_Checked_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main(S a, S b, S c, S d, S e, S f, S g, S h, S i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: S) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: S) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: S) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: S) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: S) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: S) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: S) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: S) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestCompoundAssignment_IOperation()
{
string source = @"
class C
{
static void M(int a, int b, int c, int d, int e, int f, int g, int h, int i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(21723, "https://github.com/dotnet/roslyn/issues/21723")]
public void TestCompoundLiftedAssignment_IOperation()
{
string source = @"
class C
{
static void M(int a, int? b)
{
/*<bind>*/a += b/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add, IsLifted) (OperationKind.CompoundAssignment, Type: System.Int32, IsInvalid) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'b')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
// /*<bind>*/a += b/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a += b").WithArguments("int?", "int").WithLocation(6, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestCompoundAssignment_Checked_IOperation()
{
string source = @"
class C
{
static void M(int a, int b, int c, int d, int e, int f, int g, int h, int i)
/*<bind>*/{
checked
{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestCompoundAssignment_Unchecked_IOperation()
{
string source = @"
class C
{
static void M(int a, int b, int c, int d, int e, int f, int g, int h, int i)
/*<bind>*/{
unchecked
{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUserDefinedBinaryOperatorOverloadResolution()
{
TestOperatorKinds(@"
using System;
struct S
{
public static int operator + (S x1, S x2) { return 1; }
public static int? operator - (S x1, S? x2) { return 1; }
public static S operator & (S x1, S x2) { return x1; }
public static bool operator true(S? x1) { return true; }
public static bool operator false(S? x1) { return false; }
}
class B
{
public static bool operator ==(B b1, B b2) { return true; }
public static bool operator !=(B b1, B b2) { return true; }
}
class D : B {}
class C
{
static void M()
{
bool f;
B b = null;
D d = null;
S s1 = new S();
S? s2 = s1;
int i1;
int? i2;
i1 = s1 + s1; //-UserDefinedAddition
i2 = s1 + s2; //-LiftedUserDefinedAddition
i2 = s2 + s1; //-LiftedUserDefinedAddition
i2 = s2 + s2; //-LiftedUserDefinedAddition
// No lifted form.
i2 = s1 - s1; //-UserDefinedSubtraction
i2 = s1 - s2; //-UserDefinedSubtraction
f = b == b; //-UserDefinedEqual
f = b == d; //-UserDefinedEqual
f = d == b; //-UserDefinedEqual
f = d == d; //-UserDefinedEqual
s1 = s1 & s1; //-UserDefinedAnd
s2 = s2 & s1; //-LiftedUserDefinedAnd
s2 = s1 & s2; //-LiftedUserDefinedAnd
s2 = s2 & s2; //-LiftedUserDefinedAnd
// No lifted form.
s1 = s1 && s1; //-LogicalUserDefinedAnd
// UNDONE: More tests
}
}");
}
[Fact]
public void TestUserDefinedUnaryOperatorOverloadResolution()
{
TestOperatorKinds(@"
using System;
struct S
{
public static int operator +(S s) { return 1; }
public static int operator -(S? s) { return 2; }
public static int operator !(S s) { return 3; }
public static int operator ~(S s) { return 4; }
public static S operator ++(S s) { return s; }
public static S operator --(S? s) { return (S)s; }
}
class C
{
static void M()
{
S s1 = new S();
S? s2 = s1;
int i1;
int? i2;
i1 = +s1; //-UserDefinedUnaryPlus
i2 = +s2; //-LiftedUserDefinedUnaryPlus
// No lifted form.
i1 = -s1; //-UserDefinedUnaryMinus
i1 = -s2; //-UserDefinedUnaryMinus
i1 = !s1; //-UserDefinedLogicalNegation
i2 = !s2; //-LiftedUserDefinedLogicalNegation
i1 = ~s1; //-UserDefinedBitwiseComplement
i2 = ~s2; //-LiftedUserDefinedBitwiseComplement
s1++; //-UserDefinedPostfixIncrement
s2++; //-LiftedUserDefinedPostfixIncrement
++s1; //-UserDefinedPrefixIncrement
++s2; //-LiftedUserDefinedPrefixIncrement
// No lifted form
s1--; //-UserDefinedPostfixDecrement
s2--; //-UserDefinedPostfixDecrement
}
}");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedUnaryOperatorOverloadResolution_IOperation()
{
string source = @"
using System;
struct S
{
public static int operator +(S s) { return 1; }
public static int operator -(S? s) { return 2; }
public static int operator !(S s) { return 3; }
public static int operator ~(S s) { return 4; }
public static S operator ++(S s) { return s; }
public static S operator --(S? s) { return (S)s; }
}
class C
{
static void M(S s1, S? s2, int i1, int? i2)
/*<bind>*/{
i1 = +s1; //-UserDefinedUnaryPlus
i2 = +s2; //-LiftedUserDefinedUnaryPlus
// No lifted form.
i1 = -s1; //-UserDefinedUnaryMinus
i1 = -s2; //-UserDefinedUnaryMinus
i1 = !s1; //-UserDefinedLogicalNegation
i2 = !s2; //-LiftedUserDefinedLogicalNegation
i1 = ~s1; //-UserDefinedBitwiseComplement
i2 = ~s2; //-LiftedUserDefinedBitwiseComplement
s1++; //-UserDefinedPostfixIncrement
s2++; //-LiftedUserDefinedPostfixIncrement
++s1; //-UserDefinedPrefixIncrement
++s2; //-LiftedUserDefinedPrefixIncrement
// No lifted form
s1--; //-UserDefinedPostfixDecrement
s2--; //-UserDefinedPostfixDecrement
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (14 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = +s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = +s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: System.Int32 S.op_UnaryPlus(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '+s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = +s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = +s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.Plus, IsLifted) (OperatorMethod: System.Int32 S.op_UnaryPlus(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '+s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = -s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = -s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: System.Int32 S.op_UnaryNegation(S? s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '-s1')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = -s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = -s2')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: System.Int32 S.op_UnaryNegation(S? s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '-s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = !s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = !s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: System.Int32 S.op_LogicalNot(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '!s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = !s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = !s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.Not, IsLifted) (OperatorMethod: System.Int32 S.op_LogicalNot(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '!s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = ~s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = ~s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: System.Int32 S.op_OnesComplement(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '~s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = ~s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = ~s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation, IsLifted) (OperatorMethod: System.Int32 S.op_OnesComplement(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '~s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's1++;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S) (Syntax: 's1++')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's2++;')
Expression:
IIncrementOrDecrementOperation (Postfix, IsLifted) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S?) (Syntax: 's2++')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '++s1;')
Expression:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S) (Syntax: '++s1')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '++s2;')
Expression:
IIncrementOrDecrementOperation (Prefix, IsLifted) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S?) (Syntax: '++s2')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's1--;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S? s)) (OperationKind.Decrement, Type: S) (Syntax: 's1--')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's2--;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S? s)) (OperationKind.Decrement, Type: S?) (Syntax: 's2--')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type
// public static S operator --(S? s) { return (S)s; }
Diagnostic(ErrorCode.ERR_BadIncDecRetType, "--").WithLocation(10, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUnaryOperatorOverloadingErrors()
{
var source = @"
class C
{
// UNDONE: Write tests for the rest of them
void M(bool b)
{
if(!1) {}
b++;
error++;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,12): error CS0023: Operator '!' cannot be applied to operand of type 'int'
// if(!1) {}
Diagnostic(ErrorCode.ERR_BadUnaryOp, "!1").WithArguments("!", "int").WithLocation(7, 12),
// (8,9): error CS0023: Operator '++' cannot be applied to operand of type 'bool'
// b++;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "b++").WithArguments("++", "bool").WithLocation(8, 9),
// (9,9): error CS0103: The name 'error' does not exist in the current context
// error++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var negOne = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("!1", negOne.ToString());
var type1 = model.GetTypeInfo(negOne).Type;
Assert.Equal("?", type1.ToTestDisplayString());
Assert.True(type1.IsErrorType());
var boolPlusPlus = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ElementAt(0);
Assert.Equal("b++", boolPlusPlus.ToString());
var type2 = model.GetTypeInfo(boolPlusPlus).Type;
Assert.Equal("?", type2.ToTestDisplayString());
Assert.True(type2.IsErrorType());
var errorPlusPlus = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ElementAt(1);
Assert.Equal("error++", errorPlusPlus.ToString());
var type3 = model.GetTypeInfo(errorPlusPlus).Type;
Assert.Equal("?", type3.ToTestDisplayString());
Assert.True(type3.IsErrorType());
}
[Fact]
public void TestBinaryOperatorOverloadingErrors()
{
// The native compiler and Roslyn report slightly different errors here.
// The native compiler reports CS0019 when attempting to add or compare long and ulong:
// that is "operator cannot be applied to operands of type long and ulong". This is
// correct but not as specific as it could be; the error is actually because overload
// resolution is ambiguous. The double + double --> double, float + float --> float
// and decimal + decimal --> decimal operators are all applicable but overload resolution
// finds that this set of applicable operators is ambiguous; float is better than double,
// but neither float nor decimal is better than the other.
//
// Roslyn produces the more accurate error; this is an ambiguity.
//
// Comparing string and exception is not ambiguous; the only applicable operator
// is the reference equality operator, and it requires that its operand types be
// convertible to each other.
string source = @"
class C
{
bool N() { return false; }
void M()
{
long i64 = 1;
ulong ui64 = 1;
System.String s1 = null;
System.Exception ex1 = null;
object o1 = i64 + ui64; // CS0034
bool b1 = i64 == ui64; // CS0034
bool b2 = s1 == ex1; // CS0019
bool b3 = (object)s1 == ex1; // legal!
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,21): error CS0034: Operator '+' is ambiguous on operands of type 'long' and 'ulong'
// object o1 = i64 + ui64; // CS0034
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i64 + ui64").WithArguments("+", "long", "ulong"),
// (12,19): error CS0034: Operator '==' is ambiguous on operands of type 'long' and 'ulong'
// bool b1 = i64 == ui64; // CS0034
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i64 == ui64").WithArguments("==", "long", "ulong"),
// (13,19): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'System.Exception'
// bool b2 = s1 == ex1; // CS0019
Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 == ex1").WithArguments("==", "string", "System.Exception"));
}
[Fact]
public void TestCompoundOperatorErrors()
{
var source = @"
class C
{
// UNDONE: Add more error cases
class D : C {}
public static C operator + (C c1, C c2) { return c1; }
public int ReadOnly { get { return 0; } }
public int WriteOnly { set { } }
void M()
{
C c = new C();
D d = new D();
c.ReadOnly += 1;
c.WriteOnly += 1;
int i32 = 1;
long i64 = 1;
// If we have x += y and the + is a built-in operator then
// the result must be *explicitly* convertible to x, and y
// must be *implicitly* convertible to x.
//
// If the + is a user-defined operator then the result must
// be *implicitly* convertible to x, and y need not have
// any relationship with x.
// Overload resolution resolves this as long + long --> long.
// The result is explicitly convertible to int, but the right-hand
// side is not, so this is an error.
i32 += i64;
// In the user-defined conversion, the result of the addition must
// be *implicitly* convertible to the left hand side:
d += c;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (17,9): error CS0200: Property or indexer 'C.ReadOnly' cannot be assigned to -- it is read only
// c.ReadOnly += 1;
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.ReadOnly").WithArguments("C.ReadOnly").WithLocation(17, 9),
// (18,9): error CS0154: The property or indexer 'C.WriteOnly' cannot be used in this context because it lacks the get accessor
// c.WriteOnly += 1;
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.WriteOnly").WithArguments("C.WriteOnly").WithLocation(18, 9),
// (34,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
// i32 += i64;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "i32 += i64").WithArguments("long", "int").WithLocation(34, 9),
// (39,9): error CS0266: Cannot implicitly convert type 'C' to 'C.D'. An explicit conversion exists (are you missing a cast?)
// d += c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "d += c").WithArguments("C", "C.D").WithLocation(39, 9));
}
[Fact]
public void TestOperatorOverloadResolution()
{
// UNDONE: User-defined operators
// UNDONE: TestOverloadResolution(GenerateTest(PostfixIncrementTemplate, "++", "PostfixIncrement"));
// UNDONE: TestOverloadResolution(GenerateTest(PostfixIncrementTemplate, "--", "PostfixDecrement"));
TestOperatorKinds(GenerateTest(PrefixIncrementTemplate, "++", "PrefixIncrement"));
TestOperatorKinds(GenerateTest(PrefixIncrementTemplate, "--", "PrefixDecrement"));
// UNDONE: Pointer ++ --
TestOperatorKinds(UnaryPlus);
TestOperatorKinds(UnaryMinus);
TestOperatorKinds(LogicalNegation);
TestOperatorKinds(BitwiseComplement);
TestOperatorKinds(EnumAddition);
TestOperatorKinds(StringAddition);
TestOperatorKinds(DelegateAddition);
// UNDONE: Pointer addition
TestOperatorKinds(EnumSubtraction);
TestOperatorKinds(DelegateSubtraction);
// UNDONE: Pointer subtraction
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "+", "Addition"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "-", "Subtraction"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "*", "Multiplication"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "/", "Division"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "%", "Remainder"));
TestOperatorKinds(GenerateTest(ShiftTemplate, "<<", "LeftShift"));
TestOperatorKinds(GenerateTest(ShiftTemplate, ">>", "RightShift"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "==", "Equal"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "!=", "NotEqual"));
TestOperatorKinds(GenerateTest(EqualityTemplate, "!=", "NotEqual"));
TestOperatorKinds(GenerateTest(EqualityTemplate, "!=", "NotEqual"));
// UNDONE: Pointer equality
TestOperatorKinds(GenerateTest(ComparisonTemplate, ">", "GreaterThan"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, ">=", "GreaterThanOrEqual"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, "<", "LessThan"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, "<=", "LessThanOrEqual"));
TestOperatorKinds(GenerateTest(LogicTemplate, "^", "Xor"));
TestOperatorKinds(GenerateTest(LogicTemplate, "&", "And"));
TestOperatorKinds(GenerateTest(LogicTemplate, "|", "Or"));
TestOperatorKinds(GenerateTest(ShortCircuitTemplate, "&&", "And"));
TestOperatorKinds(GenerateTest(ShortCircuitTemplate, "||", "Or"));
}
[Fact]
public void TestEnumOperatorOverloadResolution()
{
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "^", "Xor"));
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "&", "And"));
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "|", "Or"));
}
[Fact]
public void TestConstantOperatorOverloadResolution()
{
string code =
@"class C
{
static void F(object o) { }
static void M()
{
const short ci16 = 1;
uint u32 = 1;
F(u32 + 1); //-UIntAddition
F(2 + u32); //-UIntAddition
F(u32 + ci16); //-LongAddition
F(u32 + int.MaxValue); //-UIntAddition
F(u32 + (-1)); //-LongAddition
//-IntUnaryMinus
F(u32 + long.MaxValue); //-LongAddition
int i32 = 2;
F(i32 + 1); //-IntAddition
F(2 + i32); //-IntAddition
F(i32 + ci16); //-IntAddition
F(i32 + int.MaxValue); //-IntAddition
F(i32 + (-1)); //-IntAddition
//-IntUnaryMinus
}
}
";
TestOperatorKinds(code);
}
private void TestBoundTree(string source, System.Func<IEnumerable<KeyValuePair<TreeDumperNode, TreeDumperNode>>, IEnumerable<string>> query)
{
// The mechanism of this test is: we build the bound tree for the code passed in and then extract
// from it the nodes that describe the operators. We then compare the description of
// the operators given to the comment that follows the use of the operator.
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
var diagnostics = new DiagnosticBag();
var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics));
var tree = BoundTreeDumperNodeProducer.MakeTree(block);
var results = string.Join("\n",
query(tree.PreorderTraversal())
.ToArray());
var expected = string.Join("\n", source
.Split(new[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries)
.Where(x => x.Contains("//-"))
.Select(x => x.Substring(x.IndexOf("//-", StringComparison.Ordinal) + 3).Trim())
.ToArray());
Assert.Equal(expected, results);
}
private void TestOperatorKinds(string source)
{
// The mechanism of this test is: we build the bound tree for the code passed in and then extract
// from it the nodes that describe the operators. We then compare the description of
// the operators given to the comment that follows the use of the operator.
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "operatorKind"
where node.Value != null
select node.Value.ToString());
}
private void TestCompoundAssignment(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node != null && (node.Text == "eventAssignmentOperator" || node.Text == "compoundAssignmentOperator")
select string.Join(" ", from child in node.Children
where child.Text == "@operator" ||
child.Text == "isAddition" ||
child.Text == "isDynamic" ||
child.Text == "leftConversion" ||
child.Text == "finalConversion"
select child.Text + ": " + (child.Text == "@operator" ? ((BinaryOperatorSignature)child.Value).Kind.ToString() : child.Value.ToString())));
}
private void TestTypes(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "type"
select edge.Key.Text + ": " + (node.Value != null ? node.Value.ToString() : "<null>"));
}
private static string FormatTypeArgumentList(ImmutableArray<TypeWithAnnotations>? arguments)
{
if (arguments == null || arguments.Value.IsEmpty)
{
return "";
}
string s = "<";
for (int i = 0; i < arguments.Value.Length; ++i)
{
if (i != 0)
{
s += ", ";
}
s += arguments.Value[i].Type.ToString();
}
return s + ">";
}
private void TestDynamicMemberAccessCore(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "dynamicMemberAccess"
let name = node["name"]
let typeArguments = node["typeArgumentsOpt"].Value as ImmutableArray<TypeWithAnnotations>?
select name.Value.ToString() + FormatTypeArgumentList(typeArguments));
}
private static string GenerateTest(string template, string op, string opkind)
{
string result = template.Replace("OPERATOR", op);
result = result.Replace("KIND", opkind);
return result;
}
#region "Constant String"
private const string Prefix = @"
class C
{
enum E { }
void N(params object[] p) {}
delegate void D();
void M()
{
E e1;
E e2;
string s1 = null;
string s2 = null;
object o1 = null;
object o2 = null;
bool bln;
bool? nbln;
D d1 = null;
D d2 = null;
int i = 1;
E e = 0;
int? ni = 1;
E? ne = 0;
int i1 = 0;
char chr;
sbyte i08 = 1;
short i16 = 1;
int i32 = 1;
long i64 = 1;
byte u08 = 1;
ushort u16 = 1;
uint u32 = 1;
ulong u64 = 1;
float r32 = 1;
double r64 = 1;
decimal dec; // UNDONE: Decimal constants not supported yet.
char? nchr = null;
sbyte? ni08 = 1;
short? ni16 = 1;
int? ni32 = 1;
long? ni64 = 1;
byte? nu08 = 1;
ushort? nu16 = 1;
uint? nu32 = 1;
ulong? nu64 = 1;
float? nr32 = 1;
double? nr64 = 1;
decimal? ndec; // UNDONE: Decimal constants not supported yet.
N(
";
private const string Postfix = @"
);
}
}
";
private const string EnumAddition = Prefix + @"
i + e, //-UnderlyingAndEnumAddition
i + ne, //-LiftedUnderlyingAndEnumAddition
e + i, //-EnumAndUnderlyingAddition
e + ni, //-LiftedEnumAndUnderlyingAddition
ni + e, //-LiftedUnderlyingAndEnumAddition
ni + ne, //-LiftedUnderlyingAndEnumAddition
ne + i, //-LiftedEnumAndUnderlyingAddition
ne + ni //-LiftedEnumAndUnderlyingAddition" + Postfix;
private const string DelegateAddition = Prefix + @"
d1 + d2 //-DelegateCombination" + Postfix;
private const string StringAddition = Prefix + @"
s1 + s1, //-StringConcatenation
s1 + o1, //-StringAndObjectConcatenation
i1 + s1 //-ObjectAndStringConcatenation" + Postfix;
private const string ArithmeticTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR r32, //-FloatKIND
chr OPERATOR r64, //-DoubleKIND
chr OPERATOR dec, //-DecimalKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
chr OPERATOR nr32, //-LiftedFloatKIND
chr OPERATOR nr64, //-LiftedDoubleKIND
chr OPERATOR ndec, //-LiftedDecimalKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64, (ambiguous)
i16 OPERATOR r32, //-FloatKIND
i16 OPERATOR r64, //-DoubleKIND
i16 OPERATOR dec, //-DecimalKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
// i16 OPERATOR nu64, (ambiguous)
i16 OPERATOR nr32, //-LiftedFloatKIND
i16 OPERATOR nr64, //-LiftedDoubleKIND
i16 OPERATOR ndec, //-LiftedDecimalKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
// i32 OPERATOR u64, (ambiguous)
i32 OPERATOR r32, //-FloatKIND
i32 OPERATOR r64, //-DoubleKIND
i32 OPERATOR dec, //-DecimalKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
// i32 OPERATOR nu64, (ambiguous)
i32 OPERATOR nr32, //-LiftedFloatKIND
i32 OPERATOR nr64, //-LiftedDoubleKIND
i32 OPERATOR ndec, //-LiftedDecimalKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
// i64 OPERATOR u64, (ambiguous)
i64 OPERATOR r32, //-FloatKIND
i64 OPERATOR r64, //-DoubleKIND
i64 OPERATOR dec, //-DecimalKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
// i64 OPERATOR nu64, (ambiguous)
i64 OPERATOR nr32, //-LiftedFloatKIND
i64 OPERATOR nr64, //-LiftedDoubleKIND
i64 OPERATOR ndec, //-LiftedDecimalKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
u16 OPERATOR u64, //-ULongKIND
u16 OPERATOR r32, //-FloatKIND
u16 OPERATOR r64, //-DoubleKIND
u16 OPERATOR dec, //-DecimalKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
u16 OPERATOR nu64, //-LiftedULongKIND
u16 OPERATOR nr32, //-LiftedFloatKIND
u16 OPERATOR nr64, //-LiftedDoubleKIND
u16 OPERATOR ndec, //-LiftedDecimalKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR r32, //-FloatKIND
u32 OPERATOR r64, //-DoubleKIND
u32 OPERATOR dec, //-DecimalKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR nr32, //-LiftedFloatKIND
u32 OPERATOR nr64, //-LiftedDoubleKIND
u32 OPERATOR ndec, //-LiftedDecimalKIND
u64 OPERATOR chr, //-ULongKIND
// u64 OPERATOR i16, (ambiguous)
// u64 OPERATOR i32, (ambiguous)
// u64 OPERATOR i64, (ambiguous)
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR r32, //-FloatKIND
u64 OPERATOR r64, //-DoubleKIND
u64 OPERATOR dec, //-DecimalKIND
u64 OPERATOR nchr, //-LiftedULongKIND
// u64 OPERATOR ni16, (ambiguous)
// u64 OPERATOR ni32, (ambiguous)
// u64 OPERATOR ni64, (ambiguous)
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR nr32, //-LiftedFloatKIND
u64 OPERATOR nr64, //-LiftedDoubleKIND
u64 OPERATOR ndec, //-LiftedDecimalKIND
r32 OPERATOR chr, //-FloatKIND
r32 OPERATOR i16, //-FloatKIND
r32 OPERATOR i32, //-FloatKIND
r32 OPERATOR i64, //-FloatKIND
r32 OPERATOR u16, //-FloatKIND
r32 OPERATOR u32, //-FloatKIND
r32 OPERATOR u64, //-FloatKIND
r32 OPERATOR r32, //-FloatKIND
r32 OPERATOR r64, //-DoubleKIND
// r32 OPERATOR dec, (none applicable)
r32 OPERATOR nchr, //-LiftedFloatKIND
r32 OPERATOR ni16, //-LiftedFloatKIND
r32 OPERATOR ni32, //-LiftedFloatKIND
r32 OPERATOR ni64, //-LiftedFloatKIND
r32 OPERATOR nu16, //-LiftedFloatKIND
r32 OPERATOR nu32, //-LiftedFloatKIND
r32 OPERATOR nu64, //-LiftedFloatKIND
r32 OPERATOR nr32, //-LiftedFloatKIND
r32 OPERATOR nr64, //-LiftedDoubleKIND
// r32 OPERATOR ndec, (none applicable)
r64 OPERATOR chr, //-DoubleKIND
r64 OPERATOR i16, //-DoubleKIND
r64 OPERATOR i32, //-DoubleKIND
r64 OPERATOR i64, //-DoubleKIND
r64 OPERATOR u16, //-DoubleKIND
r64 OPERATOR u32, //-DoubleKIND
r64 OPERATOR u64, //-DoubleKIND
r64 OPERATOR r32, //-DoubleKIND
r64 OPERATOR r64, //-DoubleKIND
// r64 OPERATOR dec, (none applicable)
r64 OPERATOR nchr, //-LiftedDoubleKIND
r64 OPERATOR ni16, //-LiftedDoubleKIND
r64 OPERATOR ni32, //-LiftedDoubleKIND
r64 OPERATOR ni64, //-LiftedDoubleKIND
r64 OPERATOR nu16, //-LiftedDoubleKIND
r64 OPERATOR nu32, //-LiftedDoubleKIND
r64 OPERATOR nu64, //-LiftedDoubleKIND
r64 OPERATOR nr32, //-LiftedDoubleKIND
r64 OPERATOR nr64, //-LiftedDoubleKIND
// r64 OPERATOR ndec, (none applicable)
dec OPERATOR chr, //-DecimalKIND
dec OPERATOR i16, //-DecimalKIND
dec OPERATOR i32, //-DecimalKIND
dec OPERATOR i64, //-DecimalKIND
dec OPERATOR u16, //-DecimalKIND
dec OPERATOR u32, //-DecimalKIND
dec OPERATOR u64, //-DecimalKIND
// dec OPERATOR r32, (none applicable)
// dec OPERATOR r64, (none applicable)
dec OPERATOR dec, //-DecimalKIND
dec OPERATOR nchr, //-LiftedDecimalKIND
dec OPERATOR ni16, //-LiftedDecimalKIND
dec OPERATOR ni32, //-LiftedDecimalKIND
dec OPERATOR ni64, //-LiftedDecimalKIND
dec OPERATOR nu16, //-LiftedDecimalKIND
dec OPERATOR nu32, //-LiftedDecimalKIND
dec OPERATOR nu64, //-LiftedDecimalKIND
// dec OPERATOR nr32, (none applicable)
// dec OPERATOR nr64, (none applicable)
dec OPERATOR ndec, //-LiftedDecimalKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR r32, //-LiftedFloatKIND
nchr OPERATOR r64, //-LiftedDoubleKIND
nchr OPERATOR dec, //-LiftedDecimalKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR nr32, //-LiftedFloatKIND
nchr OPERATOR nr64, //-LiftedDoubleKIND
nchr OPERATOR ndec, //-LiftedDecimalKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
// ni16 OPERATOR u64, (ambiguous)
ni16 OPERATOR r32, //-LiftedFloatKIND
ni16 OPERATOR r64, //-LiftedDoubleKIND
ni16 OPERATOR dec, //-LiftedDecimalKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
// ni16 OPERATOR nu64, (ambiguous)
ni16 OPERATOR nr32, //-LiftedFloatKIND
ni16 OPERATOR nr64, //-LiftedDoubleKIND
ni16 OPERATOR ndec, //-LiftedDecimalKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
// ni32 OPERATOR u64, (ambiguous)
ni32 OPERATOR r32, //-LiftedFloatKIND
ni32 OPERATOR r64, //-LiftedDoubleKIND
ni32 OPERATOR dec, //-LiftedDecimalKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
// ni32 OPERATOR nu64, (ambiguous)
ni32 OPERATOR nr32, //-LiftedFloatKIND
ni32 OPERATOR nr64, //-LiftedDoubleKIND
ni32 OPERATOR ndec, //-LiftedDecimalKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
// ni64 OPERATOR u64, (ambiguous)
ni64 OPERATOR r32, //-LiftedFloatKIND
ni64 OPERATOR r64, //-LiftedDoubleKIND
ni64 OPERATOR dec, //-LiftedDecimalKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
// ni64 OPERATOR nu64, (ambiguous)
ni64 OPERATOR nr32, //-LiftedFloatKIND
ni64 OPERATOR nr64, //-LiftedDoubleKIND
ni64 OPERATOR ndec, //-LiftedDecimalKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
nu16 OPERATOR u64, //-LiftedULongKIND
nu16 OPERATOR r32, //-LiftedFloatKIND
nu16 OPERATOR r64, //-LiftedDoubleKIND
nu16 OPERATOR dec, //-LiftedDecimalKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
nu16 OPERATOR nu64, //-LiftedULongKIND
nu16 OPERATOR nr32, //-LiftedFloatKIND
nu16 OPERATOR nr64, //-LiftedDoubleKIND
nu16 OPERATOR ndec, //-LiftedDecimalKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR r32, //-LiftedFloatKIND
nu32 OPERATOR r64, //-LiftedDoubleKIND
nu32 OPERATOR dec, //-LiftedDecimalKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR nr32, //-LiftedFloatKIND
nu32 OPERATOR nr64, //-LiftedDoubleKIND
nu32 OPERATOR ndec, //-LiftedDecimalKIND
nu64 OPERATOR chr, //-LiftedULongKIND
// nu64 OPERATOR i16, (ambiguous)
// nu64 OPERATOR i32, (ambiguous)
// nu64 OPERATOR i64, (ambiguous)
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR r32, //-LiftedFloatKIND
nu64 OPERATOR r64, //-LiftedDoubleKIND
nu64 OPERATOR dec, //-LiftedDecimalKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
// nu64 OPERATOR ni16, (ambiguous)
// nu64 OPERATOR ni32, (ambiguous)
// nu64 OPERATOR ni64, (ambiguous)
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR nr32, //-LiftedFloatKIND
nu64 OPERATOR nr64, //-LiftedDoubleKIND
nu64 OPERATOR ndec, //-LiftedDecimalKIND
nr32 OPERATOR chr, //-LiftedFloatKIND
nr32 OPERATOR i16, //-LiftedFloatKIND
nr32 OPERATOR i32, //-LiftedFloatKIND
nr32 OPERATOR i64, //-LiftedFloatKIND
nr32 OPERATOR u16, //-LiftedFloatKIND
nr32 OPERATOR u32, //-LiftedFloatKIND
nr32 OPERATOR u64, //-LiftedFloatKIND
nr32 OPERATOR r32, //-LiftedFloatKIND
nr32 OPERATOR r64, //-LiftedDoubleKIND
// nr32 OPERATOR dec, (none applicable)
nr32 OPERATOR nchr, //-LiftedFloatKIND
nr32 OPERATOR ni16, //-LiftedFloatKIND
nr32 OPERATOR ni32, //-LiftedFloatKIND
nr32 OPERATOR ni64, //-LiftedFloatKIND
nr32 OPERATOR nu16, //-LiftedFloatKIND
nr32 OPERATOR nu32, //-LiftedFloatKIND
nr32 OPERATOR nu64, //-LiftedFloatKIND
nr32 OPERATOR nr32, //-LiftedFloatKIND
nr32 OPERATOR nr64, //-LiftedDoubleKIND
// nr32 OPERATOR ndec, (none applicable)
nr64 OPERATOR chr, //-LiftedDoubleKIND
nr64 OPERATOR i16, //-LiftedDoubleKIND
nr64 OPERATOR i32, //-LiftedDoubleKIND
nr64 OPERATOR i64, //-LiftedDoubleKIND
nr64 OPERATOR u16, //-LiftedDoubleKIND
nr64 OPERATOR u32, //-LiftedDoubleKIND
nr64 OPERATOR u64, //-LiftedDoubleKIND
nr64 OPERATOR r32, //-LiftedDoubleKIND
nr64 OPERATOR r64, //-LiftedDoubleKIND
// nr64 OPERATOR dec, (none applicable)
nr64 OPERATOR nchr, //-LiftedDoubleKIND
nr64 OPERATOR ni16, //-LiftedDoubleKIND
nr64 OPERATOR ni32, //-LiftedDoubleKIND
nr64 OPERATOR ni64, //-LiftedDoubleKIND
nr64 OPERATOR nu16, //-LiftedDoubleKIND
nr64 OPERATOR nu32, //-LiftedDoubleKIND
nr64 OPERATOR nu64, //-LiftedDoubleKIND
nr64 OPERATOR nr32, //-LiftedDoubleKIND
nr64 OPERATOR nr64, //-LiftedDoubleKIND
// nr64 OPERATOR ndec, (none applicable)
ndec OPERATOR chr, //-LiftedDecimalKIND
ndec OPERATOR i16, //-LiftedDecimalKIND
ndec OPERATOR i32, //-LiftedDecimalKIND
ndec OPERATOR i64, //-LiftedDecimalKIND
ndec OPERATOR u16, //-LiftedDecimalKIND
ndec OPERATOR u32, //-LiftedDecimalKIND
ndec OPERATOR u64, //-LiftedDecimalKIND
// ndec OPERATOR r32, (none applicable)
// ndec OPERATOR r64, (none applicable)
ndec OPERATOR dec, //-LiftedDecimalKIND
ndec OPERATOR nchr, //-LiftedDecimalKIND
ndec OPERATOR ni16, //-LiftedDecimalKIND
ndec OPERATOR ni32, //-LiftedDecimalKIND
ndec OPERATOR ni64, //-LiftedDecimalKIND
ndec OPERATOR nu16, //-LiftedDecimalKIND
ndec OPERATOR nu32, //-LiftedDecimalKIND
ndec OPERATOR nu64, //-LiftedDecimalKIND
// ndec OPERATOR nr32, (none applicable)
// ndec OPERATOR nr64, (none applicable)
ndec OPERATOR ndec //-LiftedDecimalKIND" + Postfix;
private const string EnumSubtraction = Prefix + @"
e - e, //-EnumSubtraction
e - ne, //-LiftedEnumSubtraction
e - i, //-EnumAndUnderlyingSubtraction
e - ni, //-LiftedEnumAndUnderlyingSubtraction
ne - e, //-LiftedEnumSubtraction
ne - ne, //-LiftedEnumSubtraction
ne - i, //-LiftedEnumAndUnderlyingSubtraction
ne - ni //-LiftedEnumAndUnderlyingSubtraction" + Postfix;
private const string DelegateSubtraction = Prefix + "d1 - d2 //-DelegateRemoval" + Postfix;
private const string ShiftTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-UIntKIND
u32 OPERATOR i32, //-UIntKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedUIntKIND
u32 OPERATOR ni32, //-LiftedUIntKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u64 OPERATOR chr, //-ULongKIND
u64 OPERATOR i16, //-ULongKIND
u64 OPERATOR i32, //-ULongKIND
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR nchr, //-LiftedULongKIND
u64 OPERATOR ni16, //-LiftedULongKIND
u64 OPERATOR ni32, //-LiftedULongKIND
u64 OPERATOR nu16, //-LiftedULongKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedUIntKIND
nu32 OPERATOR i32, //-LiftedUIntKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedUIntKIND
nu32 OPERATOR ni32, //-LiftedUIntKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu64 OPERATOR chr, //-LiftedULongKIND
nu64 OPERATOR i16, //-LiftedULongKIND
nu64 OPERATOR i32, //-LiftedULongKIND
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
nu64 OPERATOR ni16, //-LiftedULongKIND
nu64 OPERATOR ni32, //-LiftedULongKIND
nu64 OPERATOR nu16 //-LiftedULongKIND
" + Postfix;
private const string LogicTemplate = Prefix + @"
bln OPERATOR bln, //-BoolKIND
bln OPERATOR nbln, //-LiftedBoolKIND
nbln OPERATOR bln, //-LiftedBoolKIND
nbln OPERATOR nbln, //-LiftedBoolKIND
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64,
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
//i16 OPERATOR nu64,
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
//i32 OPERATOR u64,
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
//i32 OPERATOR nu64,
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
//i64 OPERATOR u64,
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
//i64 OPERATOR nu64,
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
u16 OPERATOR u64, //-ULongKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
u16 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR chr, //-ULongKIND
//u64 OPERATOR i16,
//u64 OPERATOR i32,
//u64 OPERATOR i64,
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR nchr, //-LiftedULongKIND
//u64 OPERATOR ni16,
//u64 OPERATOR ni32,
//u64 OPERATOR ni64,
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
//ni16 OPERATOR u64,
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
//ni16 OPERATOR nu64,
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
//ni32 OPERATOR u64,
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
//ni32 OPERATOR nu64,
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
//ni64 OPERATOR u64,
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
//ni64 OPERATOR nu64,
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
nu16 OPERATOR u64, //-LiftedULongKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
nu16 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR chr, //-LiftedULongKIND
//nu64 OPERATOR i16,
//nu64 OPERATOR i32,
//nu64 OPERATOR i64,
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
//nu64 OPERATOR ni16,
//nu64 OPERATOR ni32,
//nu64 OPERATOR ni64,
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64 //-LiftedULongKIND
" + Postfix;
//built-in operator only works for bools (not even lifted bools)
private const string ShortCircuitTemplate = Prefix + @"
bln OPERATOR bln, //-LogicalBoolKIND
" + Postfix;
private const string EnumLogicTemplate = Prefix + @"
e OPERATOR e, //-EnumKIND
e OPERATOR ne, //-LiftedEnumKIND
ne OPERATOR e, //-LiftedEnumKIND
ne OPERATOR ne //-LiftedEnumKIND" + Postfix;
private const string ComparisonTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR r32, //-FloatKIND
chr OPERATOR r64, //-DoubleKIND
chr OPERATOR dec, //-DecimalKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
chr OPERATOR nr32, //-LiftedFloatKIND
chr OPERATOR nr64, //-LiftedDoubleKIND
chr OPERATOR ndec, //-LiftedDecimalKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64, (ambiguous)
i16 OPERATOR r32, //-FloatKIND
i16 OPERATOR r64, //-DoubleKIND
i16 OPERATOR dec, //-DecimalKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
// i16 OPERATOR nu64, (ambiguous)
i16 OPERATOR nr32, //-LiftedFloatKIND
i16 OPERATOR nr64, //-LiftedDoubleKIND
i16 OPERATOR ndec, //-LiftedDecimalKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
// i32 OPERATOR u64, (ambiguous)
i32 OPERATOR r32, //-FloatKIND
i32 OPERATOR r64, //-DoubleKIND
i32 OPERATOR dec, //-DecimalKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
// i32 OPERATOR nu64, (ambiguous)
i32 OPERATOR nr32, //-LiftedFloatKIND
i32 OPERATOR nr64, //-LiftedDoubleKIND
i32 OPERATOR ndec, //-LiftedDecimalKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
// i64 OPERATOR u64, (ambiguous)
i64 OPERATOR r32, //-FloatKIND
i64 OPERATOR r64, //-DoubleKIND
i64 OPERATOR dec, //-DecimalKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
// i64 OPERATOR nu64, (ambiguous)
i64 OPERATOR nr32, //-LiftedFloatKIND
i64 OPERATOR nr64, //-LiftedDoubleKIND
i64 OPERATOR ndec, //-LiftedDecimalKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
//u16 OPERATOR u64, (ambiguous)
u16 OPERATOR r32, //-FloatKIND
u16 OPERATOR r64, //-DoubleKIND
u16 OPERATOR dec, //-DecimalKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
//u16 OPERATOR nu64, (ambiguous)
u16 OPERATOR nr32, //-LiftedFloatKIND
u16 OPERATOR nr64, //-LiftedDoubleKIND
u16 OPERATOR ndec, //-LiftedDecimalKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR r32, //-FloatKIND
u32 OPERATOR r64, //-DoubleKIND
u32 OPERATOR dec, //-DecimalKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR nr32, //-LiftedFloatKIND
u32 OPERATOR nr64, //-LiftedDoubleKIND
u32 OPERATOR ndec, //-LiftedDecimalKIND
u64 OPERATOR chr, //-ULongKIND
// u64 OPERATOR i16, (ambiguous)
// u64 OPERATOR i32, (ambiguous)
// u64 OPERATOR i64, (ambiguous)
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR r32, //-FloatKIND
u64 OPERATOR r64, //-DoubleKIND
u64 OPERATOR dec, //-DecimalKIND
u64 OPERATOR nchr, //-LiftedULongKIND
// u64 OPERATOR ni16, (ambiguous)
// u64 OPERATOR ni32, (ambiguous)
// u64 OPERATOR ni64, (ambiguous)
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR nr32, //-LiftedFloatKIND
u64 OPERATOR nr64, //-LiftedDoubleKIND
u64 OPERATOR ndec, //-LiftedDecimalKIND
r32 OPERATOR chr, //-FloatKIND
r32 OPERATOR i16, //-FloatKIND
r32 OPERATOR i32, //-FloatKIND
r32 OPERATOR i64, //-FloatKIND
r32 OPERATOR u16, //-FloatKIND
r32 OPERATOR u32, //-FloatKIND
r32 OPERATOR u64, //-FloatKIND
r32 OPERATOR r32, //-FloatKIND
r32 OPERATOR r64, //-DoubleKIND
// r32 OPERATOR dec, (none applicable)
r32 OPERATOR nchr, //-LiftedFloatKIND
r32 OPERATOR ni16, //-LiftedFloatKIND
r32 OPERATOR ni32, //-LiftedFloatKIND
r32 OPERATOR ni64, //-LiftedFloatKIND
r32 OPERATOR nu16, //-LiftedFloatKIND
r32 OPERATOR nu32, //-LiftedFloatKIND
r32 OPERATOR nu64, //-LiftedFloatKIND
r32 OPERATOR nr32, //-LiftedFloatKIND
r32 OPERATOR nr64, //-LiftedDoubleKIND
// r32 OPERATOR ndec, (none applicable)
r64 OPERATOR chr, //-DoubleKIND
r64 OPERATOR i16, //-DoubleKIND
r64 OPERATOR i32, //-DoubleKIND
r64 OPERATOR i64, //-DoubleKIND
r64 OPERATOR u16, //-DoubleKIND
r64 OPERATOR u32, //-DoubleKIND
r64 OPERATOR u64, //-DoubleKIND
r64 OPERATOR r32, //-DoubleKIND
r64 OPERATOR r64, //-DoubleKIND
// r64 OPERATOR dec, (none applicable)
r64 OPERATOR nchr, //-LiftedDoubleKIND
r64 OPERATOR ni16, //-LiftedDoubleKIND
r64 OPERATOR ni32, //-LiftedDoubleKIND
r64 OPERATOR ni64, //-LiftedDoubleKIND
r64 OPERATOR nu16, //-LiftedDoubleKIND
r64 OPERATOR nu32, //-LiftedDoubleKIND
r64 OPERATOR nu64, //-LiftedDoubleKIND
r64 OPERATOR nr32, //-LiftedDoubleKIND
r64 OPERATOR nr64, //-LiftedDoubleKIND
// r64 OPERATOR ndec, (none applicable)
dec OPERATOR chr, //-DecimalKIND
dec OPERATOR i16, //-DecimalKIND
dec OPERATOR i32, //-DecimalKIND
dec OPERATOR i64, //-DecimalKIND
dec OPERATOR u16, //-DecimalKIND
dec OPERATOR u32, //-DecimalKIND
dec OPERATOR u64, //-DecimalKIND
// dec OPERATOR r32, (none applicable)
// dec OPERATOR r64, (none applicable)
dec OPERATOR dec, //-DecimalKIND
dec OPERATOR nchr, //-LiftedDecimalKIND
dec OPERATOR ni16, //-LiftedDecimalKIND
dec OPERATOR ni32, //-LiftedDecimalKIND
dec OPERATOR ni64, //-LiftedDecimalKIND
dec OPERATOR nu16, //-LiftedDecimalKIND
dec OPERATOR nu32, //-LiftedDecimalKIND
dec OPERATOR nu64, //-LiftedDecimalKIND
// dec OPERATOR nr32, (none applicable)
// dec OPERATOR nr64, (none applicable)
dec OPERATOR ndec, //-LiftedDecimalKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR r32, //-LiftedFloatKIND
nchr OPERATOR r64, //-LiftedDoubleKIND
nchr OPERATOR dec, //-LiftedDecimalKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR nr32, //-LiftedFloatKIND
nchr OPERATOR nr64, //-LiftedDoubleKIND
nchr OPERATOR ndec, //-LiftedDecimalKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
// ni16 OPERATOR u64, (ambiguous)
ni16 OPERATOR r32, //-LiftedFloatKIND
ni16 OPERATOR r64, //-LiftedDoubleKIND
ni16 OPERATOR dec, //-LiftedDecimalKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
// ni16 OPERATOR nu64, (ambiguous)
ni16 OPERATOR nr32, //-LiftedFloatKIND
ni16 OPERATOR nr64, //-LiftedDoubleKIND
ni16 OPERATOR ndec, //-LiftedDecimalKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
// ni32 OPERATOR u64, (ambiguous)
ni32 OPERATOR r32, //-LiftedFloatKIND
ni32 OPERATOR r64, //-LiftedDoubleKIND
ni32 OPERATOR dec, //-LiftedDecimalKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
// ni32 OPERATOR nu64, (ambiguous)
ni32 OPERATOR nr32, //-LiftedFloatKIND
ni32 OPERATOR nr64, //-LiftedDoubleKIND
ni32 OPERATOR ndec, //-LiftedDecimalKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
// ni64 OPERATOR u64, (ambiguous)
ni64 OPERATOR r32, //-LiftedFloatKIND
ni64 OPERATOR r64, //-LiftedDoubleKIND
ni64 OPERATOR dec, //-LiftedDecimalKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
// ni64 OPERATOR nu64, (ambiguous)
ni64 OPERATOR nr32, //-LiftedFloatKIND
ni64 OPERATOR nr64, //-LiftedDoubleKIND
ni64 OPERATOR ndec, //-LiftedDecimalKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
//nu16 OPERATOR u64, (ambiguous)
nu16 OPERATOR r32, //-LiftedFloatKIND
nu16 OPERATOR r64, //-LiftedDoubleKIND
nu16 OPERATOR dec, //-LiftedDecimalKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
//nu16 OPERATOR nu64, (ambiguous)
nu16 OPERATOR nr32, //-LiftedFloatKIND
nu16 OPERATOR nr64, //-LiftedDoubleKIND
nu16 OPERATOR ndec, //-LiftedDecimalKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR r32, //-LiftedFloatKIND
nu32 OPERATOR r64, //-LiftedDoubleKIND
nu32 OPERATOR dec, //-LiftedDecimalKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR nr32, //-LiftedFloatKIND
nu32 OPERATOR nr64, //-LiftedDoubleKIND
nu32 OPERATOR ndec, //-LiftedDecimalKIND
nu64 OPERATOR chr, //-LiftedULongKIND
// nu64 OPERATOR i16, (ambiguous)
// nu64 OPERATOR i32, (ambiguous)
// nu64 OPERATOR i64, (ambiguous)
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR r32, //-LiftedFloatKIND
nu64 OPERATOR r64, //-LiftedDoubleKIND
nu64 OPERATOR dec, //-LiftedDecimalKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
// nu64 OPERATOR ni16, (ambiguous)
// nu64 OPERATOR ni32, (ambiguous)
// nu64 OPERATOR ni64, (ambiguous)
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR nr32, //-LiftedFloatKIND
nu64 OPERATOR nr64, //-LiftedDoubleKIND
nu64 OPERATOR ndec, //-LiftedDecimalKIND
nr32 OPERATOR chr, //-LiftedFloatKIND
nr32 OPERATOR i16, //-LiftedFloatKIND
nr32 OPERATOR i32, //-LiftedFloatKIND
nr32 OPERATOR i64, //-LiftedFloatKIND
nr32 OPERATOR u16, //-LiftedFloatKIND
nr32 OPERATOR u32, //-LiftedFloatKIND
nr32 OPERATOR u64, //-LiftedFloatKIND
nr32 OPERATOR r32, //-LiftedFloatKIND
nr32 OPERATOR r64, //-LiftedDoubleKIND
// nr32 OPERATOR dec, (none applicable)
nr32 OPERATOR nchr, //-LiftedFloatKIND
nr32 OPERATOR ni16, //-LiftedFloatKIND
nr32 OPERATOR ni32, //-LiftedFloatKIND
nr32 OPERATOR ni64, //-LiftedFloatKIND
nr32 OPERATOR nu16, //-LiftedFloatKIND
nr32 OPERATOR nu32, //-LiftedFloatKIND
nr32 OPERATOR nu64, //-LiftedFloatKIND
nr32 OPERATOR nr32, //-LiftedFloatKIND
nr32 OPERATOR nr64, //-LiftedDoubleKIND
// nr32 OPERATOR ndec, (none applicable)
nr64 OPERATOR chr, //-LiftedDoubleKIND
nr64 OPERATOR i16, //-LiftedDoubleKIND
nr64 OPERATOR i32, //-LiftedDoubleKIND
nr64 OPERATOR i64, //-LiftedDoubleKIND
nr64 OPERATOR u16, //-LiftedDoubleKIND
nr64 OPERATOR u32, //-LiftedDoubleKIND
nr64 OPERATOR u64, //-LiftedDoubleKIND
nr64 OPERATOR r32, //-LiftedDoubleKIND
nr64 OPERATOR r64, //-LiftedDoubleKIND
// nr64 OPERATOR dec, (none applicable)
nr64 OPERATOR nchr, //-LiftedDoubleKIND
nr64 OPERATOR ni16, //-LiftedDoubleKIND
nr64 OPERATOR ni32, //-LiftedDoubleKIND
nr64 OPERATOR ni64, //-LiftedDoubleKIND
nr64 OPERATOR nu16, //-LiftedDoubleKIND
nr64 OPERATOR nu32, //-LiftedDoubleKIND
nr64 OPERATOR nu64, //-LiftedDoubleKIND
nr64 OPERATOR nr32, //-LiftedDoubleKIND
nr64 OPERATOR nr64, //-LiftedDoubleKIND
// nr64 OPERATOR ndec, (none applicable)
ndec OPERATOR chr, //-LiftedDecimalKIND
ndec OPERATOR i16, //-LiftedDecimalKIND
ndec OPERATOR i32, //-LiftedDecimalKIND
ndec OPERATOR i64, //-LiftedDecimalKIND
ndec OPERATOR u16, //-LiftedDecimalKIND
ndec OPERATOR u32, //-LiftedDecimalKIND
ndec OPERATOR u64, //-LiftedDecimalKIND
// ndec OPERATOR r32, (none applicable)
// ndec OPERATOR r64, (none applicable)
ndec OPERATOR dec, //-LiftedDecimalKIND
ndec OPERATOR nchr, //-LiftedDecimalKIND
ndec OPERATOR ni16, //-LiftedDecimalKIND
ndec OPERATOR ni32, //-LiftedDecimalKIND
ndec OPERATOR ni64, //-LiftedDecimalKIND
ndec OPERATOR nu16, //-LiftedDecimalKIND
ndec OPERATOR nu32, //-LiftedDecimalKIND
ndec OPERATOR nu64, //-LiftedDecimalKIND
// ndec OPERATOR nr32, (none applicable)
// ndec OPERATOR nr64, (none applicable)
ndec OPERATOR ndec //-LiftedDecimalKIND
" + Postfix;
private const string EqualityTemplate = Prefix + @"
e1 OPERATOR e2, //-EnumKIND
e1 OPERATOR o2, //-KIND
d1 OPERATOR d2, //-DelegateKIND
d1 OPERATOR o2, //-ObjectKIND
s1 OPERATOR s2, //-StringKIND
s1 OPERATOR o2, //-ObjectKIND
o1 OPERATOR e2, //-KIND
o1 OPERATOR d2, //-ObjectKIND
o1 OPERATOR s2, //-ObjectKIND
o1 OPERATOR o2 //-ObjectKIND" + Postfix;
private const string PostfixIncrementTemplate = Prefix + @"
e OPERATOR, //-EnumKIND
chr OPERATOR, //-CharKIND
i08 OPERATOR, //-SByteKIND
i16 OPERATOR, //-ShortKIND
i32 OPERATOR, //-IntKIND
i64 OPERATOR, //-LongKIND
u08 OPERATOR, //-ByteKIND
u16 OPERATOR, //-UShortKIND
u32 OPERATOR, //-UIntKIND
u64 OPERATOR, //-ULongKIND
r32 OPERATOR, //-FloatKIND
r64 OPERATOR, //-DoubleKIND
dec OPERATOR, //-DecimalKIND
ne OPERATOR, //-LiftedEnumKIND
nchr OPERATOR, //-LiftedCharKIND
ni08 OPERATOR, //-LiftedSByteKIND
ni16 OPERATOR, //-LiftedShortKIND
ni32 OPERATOR, //-LiftedIntKIND
ni64 OPERATOR, //-LiftedLongKIND
nu08 OPERATOR, //-LiftedByteKIND
nu16 OPERATOR, //-LiftedUShortKIND
nu32 OPERATOR, //-LiftedUIntKIND
nu64 OPERATOR, //-LiftedULongKIND
nr32 OPERATOR, //-LiftedFloatKIND
nr64 OPERATOR, //-LiftedDoubleKIND
ndec OPERATOR //-LiftedDecimalKIND
" + Postfix;
private const string PrefixIncrementTemplate = Prefix + @"
OPERATOR e , //-EnumKIND
OPERATOR chr , //-CharKIND
OPERATOR i08 , //-SByteKIND
OPERATOR i16 , //-ShortKIND
OPERATOR i32 , //-IntKIND
OPERATOR i64 , //-LongKIND
OPERATOR u08 , //-ByteKIND
OPERATOR u16 , //-UShortKIND
OPERATOR u32 , //-UIntKIND
OPERATOR u64 , //-ULongKIND
OPERATOR r32 , //-FloatKIND
OPERATOR r64 , //-DoubleKIND
OPERATOR dec , //-DecimalKIND
OPERATOR ne , //-LiftedEnumKIND
OPERATOR nchr , //-LiftedCharKIND
OPERATOR ni08 , //-LiftedSByteKIND
OPERATOR ni16 , //-LiftedShortKIND
OPERATOR ni32 , //-LiftedIntKIND
OPERATOR ni64 , //-LiftedLongKIND
OPERATOR nu08 , //-LiftedByteKIND
OPERATOR nu16 , //-LiftedUShortKIND
OPERATOR nu32 , //-LiftedUIntKIND
OPERATOR nu64 , //-LiftedULongKIND
OPERATOR nr32 , //-LiftedFloatKIND
OPERATOR nr64 , //-LiftedDoubleKIND
OPERATOR ndec //-LiftedDecimalKIND" + Postfix;
private const string UnaryPlus = Prefix + @"
+ chr, //-IntUnaryPlus
+ i08, //-IntUnaryPlus
+ i16, //-IntUnaryPlus
+ i32, //-IntUnaryPlus
+ i64, //-LongUnaryPlus
+ u08, //-IntUnaryPlus
+ u16, //-IntUnaryPlus
+ u32, //-UIntUnaryPlus
+ u64, //-ULongUnaryPlus
+ r32, //-FloatUnaryPlus
+ r64, //-DoubleUnaryPlus
+ dec, //-DecimalUnaryPlus
+ nchr, //-LiftedIntUnaryPlus
+ ni08, //-LiftedIntUnaryPlus
+ ni16, //-LiftedIntUnaryPlus
+ ni32, //-LiftedIntUnaryPlus
+ ni64, //-LiftedLongUnaryPlus
+ nu08, //-LiftedIntUnaryPlus
+ nu16, //-LiftedIntUnaryPlus
+ nu32, //-LiftedUIntUnaryPlus
+ nu64, //-LiftedULongUnaryPlus
+ nr32, //-LiftedFloatUnaryPlus
+ nr64, //-LiftedDoubleUnaryPlus
+ ndec //-LiftedDecimalUnaryPlus" + Postfix;
private const string UnaryMinus = Prefix + @"
- chr, //-IntUnaryMinus
- i08, //-IntUnaryMinus
- i16, //-IntUnaryMinus
- i32, //-IntUnaryMinus
- i64, //-LongUnaryMinus
- u08, //-IntUnaryMinus
- u16, //-IntUnaryMinus
- u32, //-LongUnaryMinus
- r32, //-FloatUnaryMinus
- r64, //-DoubleUnaryMinus
- dec, //-DecimalUnaryMinus
- nchr, //-LiftedIntUnaryMinus
- ni08, //-LiftedIntUnaryMinus
- ni16, //-LiftedIntUnaryMinus
- ni32, //-LiftedIntUnaryMinus
- ni64, //-LiftedLongUnaryMinus
- nu08, //-LiftedIntUnaryMinus
- nu16, //-LiftedIntUnaryMinus
- nu32, //-LiftedLongUnaryMinus
- nr32, //-LiftedFloatUnaryMinus
- nr64, //-LiftedDoubleUnaryMinus
- ndec //-LiftedDecimalUnaryMinus" + Postfix;
private const string LogicalNegation = Prefix + @"
! bln, //-BoolLogicalNegation
! nbln //-LiftedBoolLogicalNegation" + Postfix;
private const string BitwiseComplement = Prefix + @"
~ e, //-EnumBitwiseComplement
~ chr, //-IntBitwiseComplement
~ i08, //-IntBitwiseComplement
~ i16, //-IntBitwiseComplement
~ i32, //-IntBitwiseComplement
~ i64, //-LongBitwiseComplement
~ u08, //-IntBitwiseComplement
~ u16, //-IntBitwiseComplement
~ u32, //-UIntBitwiseComplement
~ u64, //-ULongBitwiseComplement
~ ne, //-LiftedEnumBitwiseComplement
~ nchr, //-LiftedIntBitwiseComplement
~ ni08, //-LiftedIntBitwiseComplement
~ ni16, //-LiftedIntBitwiseComplement
~ ni32, //-LiftedIntBitwiseComplement
~ ni64, //-LiftedLongBitwiseComplement
~ nu08, //-LiftedIntBitwiseComplement
~ nu16, //-LiftedIntBitwiseComplement
~ nu32, //-LiftedUIntBitwiseComplement
~ nu64 //-LiftedULongBitwiseComplement
);
}
}" + Postfix;
#endregion
[Fact, WorkItem(527598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527598")]
public void UserDefinedOperatorOnPointerType()
{
CreateCompilation(@"
unsafe struct A
{
public static implicit operator int*(A x) { return null; }
static void M()
{
var x = new A();
int* y = null;
var z = x - y; // Dev11 generates CS0019...should compile
}
}
", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
// add better verification once this is implemented
}
[Fact]
public void TestNullCoalesce_Dynamic()
{
var source = @"
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
Dynamic_b_constant_null_a();
Dynamic_b_constant_null_a_nullable();
Dynamic_b_constant_not_null_a_nullable();
Dynamic_b_not_null_a();
Dynamic_b_not_null_a_nullable(10);
return 0;
}
public static D Dynamic_b_constant_null_a()
{
dynamic b = new D();
D a = null;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_constant_null_a_nullable()
{
dynamic b = new D();
int? a = null;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_constant_not_null_a_nullable()
{
dynamic b = new D();
int? a = 10;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_not_null_a()
{
dynamic b = new D();
D a = new E();
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_not_null_a_nullable(int? c)
{
dynamic b = new D();
int? a = c;
dynamic z = a ?? b;
return z;
}
}
";
var compilation = CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(541147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541147")]
[Fact]
public void TestNullCoalesceWithMethodGroup()
{
var source = @"
using System;
static class Program
{
static void Main()
{
Action a = Main ?? Main;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main ?? Main").WithArguments("??", "method group", "method group"));
}
[WorkItem(541149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541149")]
[Fact]
public void TestNullCoalesceWithLambda()
{
var source = @"
using System;
static class Program
{
static void Main()
{
const Action<int> a = null;
var b = a ?? (() => { });
}
}
";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? (() => { })").WithArguments("??", "System.Action<int>", "lambda expression"));
}
[WorkItem(541148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541148")]
[Fact]
public void TestNullCoalesceWithConstNonNullExpression()
{
var source = @"
using System;
static class Program
{
static void Main()
{
const string x = ""A"";
string y;
string z = x ?? y;
Console.WriteLine(z);
}
}
";
CompileAndVerify(source, expectedOutput: "A");
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_01()
{
var source = @"
class B
{
static void Main()
{
A a = null;
B b = null;
var c = a ?? b;
}
public static implicit operator A(B x)
{
return new A();
}
}
class A
{
public static implicit operator A(B x)
{
return new A();
}
public static implicit operator B(A x)
{
return new B();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,22): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c = a ?? b;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_02()
{
var source = @"
struct B
{
static void Main()
{
A? a = null;
B b;
var c = a ?? b;
}
public static implicit operator A(B x)
{
return new A();
}
}
struct A
{
public static implicit operator A(B x)
{
return new A();
}
public static implicit operator B(A x)
{
return new B();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,22): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c = a ?? b;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_03()
{
var source = @"
struct B
{
static void Main()
{
A a2;
B? b2 = null;
var c2 = b2 ?? a2;
}
public static implicit operator A(B x)
{
return new A();
}
}
struct A
{
public static implicit operator A(B x)
{
return new A();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,18): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c2 = b2 ?? a2;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b2").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(541343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541343")]
[Fact]
public void TestAsOperator_Bug8014()
{
var source = @"
using System;
class Program
{
static void Main()
{
object y = null as object ?? null;
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty);
}
[WorkItem(542090, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542090")]
[Fact]
public void TestAsOperatorWithImplicitConversion()
{
var source = @"
using System;
class Program
{
static void Main()
{
object o = 5 as object;
string s = ""str"" as string;
s = null as string;
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[Fact]
public void TestDefaultOperator_ConstantDateTime()
{
var source = @"
using System;
namespace N2
{
class X
{
public static void Main()
{
}
public static DateTime Goo()
{
return default(DateTime);
}
}
}";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestDefaultOperator_Dynamic()
{
// "default(dynamic)" has constant value null.
var source = @"
using System;
public class X
{
public static void Main()
{
const object obj = default(dynamic);
Console.Write(obj == null);
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "True"); ;
source = @"
using System;
public class C<T> { }
public class X
{
public X(dynamic param = default(dynamic)) { Console.WriteLine(param == null); }
public static void Main()
{
Console.Write(default(dynamic));
Console.Write(default(C<dynamic>));
Console.WriteLine(default(dynamic) == null);
Console.WriteLine(default(C<dynamic>) == null);
object x = default(dynamic);
Console.WriteLine(x == null);
var unused = new X();
}
}";
comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics();
// "default(dynamic)" has type dynamic
source = @"
public class X
{
public X(object param = default(dynamic)) {}
}";
comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (4,21): error CS1750: A value of type 'dynamic' cannot be used as a default parameter because there are no standard conversions to type 'object'
// public X(object param = default(dynamic)) {}
Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "param").WithArguments("dynamic", "object"));
}
[WorkItem(537876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537876")]
[Fact]
public void TestEnumOrAssign()
{
var source = @"
enum F
{
A,
B,
C
}
class Program
{
static void Main(string[] args)
{
F x = F.A;
x |= F.B;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542072")]
[Fact]
public void TestEnumLogicalWithLiteralZero_9042()
{
var source = @"
enum F { A }
class Program
{
static void Main()
{
M(F.A | 0);
M(0 | F.A);
M(F.A & 0);
M(0 & F.A);
M(F.A ^ 0);
M(0 ^ F.A);
}
static void M(F f) {}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542073, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542073")]
[Fact]
public void TestEnumCompoundAddition_9043()
{
var source = @"
enum F { A, B }
class Program
{
static void Main()
{
F f = F.A;
f += 1;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542086")]
[Fact]
public void TestStringCompoundAddition_9146()
{
var source = @"
class Test
{
public static void Main()
{
int i = 0;
string s = ""i="";
s += i;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestOpTrueInBooleanExpression()
{
var source = @"
class Program
{
struct C
{
public int x;
public static bool operator true(C c) { return c.x != 0; }
public static bool operator false(C c) { return c.x == 0; }
public static bool operator true(C? c) { return c.HasValue && c.Value.x != 0; }
public static bool operator false(C? c) { return c.HasValue && c.Value.x == 0; }
}
static void Main()
{
C c = new C();
c.x = 1;
if (c)
{
System.Console.WriteLine(1);
}
while(c)
{
System.Console.WriteLine(2);
c.x--;
}
for(c.x = 1; c; c.x--)
System.Console.WriteLine(3);
c.x = 1;
do
{
System.Console.WriteLine(4);
c.x--;
}
while(c);
System.Console.WriteLine(c ? 6 : 5);
C? c2 = c;
System.Console.WriteLine(c2 ? 7 : 8);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestOpTrueInBooleanExpressionError()
{
// operator true does not lift to nullable.
var source = @"
class Program
{
struct C
{
public int x;
public static bool operator true(C c) { return c.x != 0; }
public static bool operator false(C c) { return c.x == 0; }
}
static void Main()
{
C? c = new C();
if (c)
{
System.Console.WriteLine(1);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,13): error CS0029: Cannot implicitly convert type 'Program.C?' to 'bool'
// if (c)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c").WithArguments("Program.C?", "bool"),
// (6,20): warning CS0649: Field 'Program.C.x' is never assigned to, and will always have its default value 0
// public int x;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Program.C.x", "0")
);
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294")]
[Fact()]
public void TestAsOperatorWithTypeParameter()
{
// SPEC: Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:
// SPEC: - An identity (�6.1.1), implicit nullable (�6.1.4), implicit reference (�6.1.6), boxing (�6.1.7),
// SPEC: explicit nullable (�6.2.3), explicit reference (�6.2.4), or unboxing (�6.2.5) conversion exists
// SPEC: from E to T.
// SPEC: - The type of E or T is an open type.
// SPEC: - E is the null literal.
// SPEC VIOLATION: The specification unintentionally allows the case where requirement 2 above:
// SPEC VIOLATION: "The type of E or T is an open type" is true, but type of E is void type, i.e. T is an open type.
// SPEC VIOLATION: Dev10 compiler correctly generates an error for this case and we will maintain compatibility.
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action>();
}
static void Goo<T>() where T : class
{
object o = Main() as T;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (13,20): error CS0039: Cannot convert type 'void' to 'T' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object o = Main() as T;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "Main() as T").WithArguments("void", "T"));
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294")]
[Fact()]
public void TestIsOperatorWithTypeParameter_01()
{
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action>();
}
static void Goo<T>() where T : class
{
bool b = Main() is T;
}
}
";
// NOTE: Dev10 violates the SPEC for this test case and generates
// NOTE: an error ERR_NoExplicitBuiltinConv if the target type
// NOTE: is an open type. According to the specification, the result
// NOTE: is always false, but no compile time error occurs.
// NOTE: We follow the specification and generate WRN_IsAlwaysFalse
// NOTE: instead of an error.
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (13,18): warning CS0184: The given expression is never of the provided ('T') type
// bool b = Main() is T;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "Main() is T").WithArguments("T"));
}
[Fact]
[WorkItem(34679, "https://github.com/dotnet/roslyn/issues/34679")]
public void TestIsOperatorWithTypeParameter_02()
{
var source = @"
class A<T>
{
public virtual void M1<S>(S x) where S : T { }
}
class C : A<int?>
{
static void Main()
{
var x = new C();
int? y = null;
x.M1(y);
x.Test(y);
y = 0;
x.M1(y);
x.Test(y);
}
void Test(int? x)
{
if (x is System.ValueType)
{
System.Console.WriteLine(""Test if"");
}
else
{
System.Console.WriteLine(""Test else"");
}
}
public override void M1<S>(S x)
{
if (x is System.ValueType)
{
System.Console.WriteLine(""M1 if"");
}
else
{
System.Console.WriteLine(""M1 else"");
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput:
@"M1 else
Test else
M1 if
Test if");
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithGenericContainingType()
{
var source = @"
class Program
{
static void Goo<T>(
Outer<T>.C c1, Outer<int>.C c2,
Outer<T>.S s1, Outer<int>.S s2,
Outer<T>.E e1, Outer<int>.E e2)
{
bool b;
b = c1 is Outer<T>.C; // Deferred to runtime - null check.
b = c1 is Outer<int>.C; // Deferred to runtime - null check.
b = c1 is Outer<long>.C; // Deferred to runtime - null check.
b = c2 is Outer<T>.C; // Deferred to runtime - null check.
b = c2 is Outer<int>.C; // Deferred to runtime - null check.
b = c2 is Outer<long>.C; // Always false.
b = s1 is Outer<T>.S; // Always true.
b = s1 is Outer<int>.S; // Deferred to runtime - type unification.
b = s1 is Outer<long>.S; // Deferred to runtime - type unification.
b = s2 is Outer<T>.S; // Deferred to runtime - type unification.
b = s2 is Outer<int>.S; // Always true.
b = s2 is Outer<long>.S; // Always false.
b = e1 is Outer<T>.E; // Always true.
b = e1 is Outer<int>.E; // Deferred to runtime - type unification.
b = e1 is Outer<long>.E; // Deferred to runtime - type unification.
b = e2 is Outer<T>.E; // Deferred to runtime - type unification.
b = e2 is Outer<int>.E; // Always true.
b = e2 is Outer<long>.E; // Always false.
}
}
class Outer<T>
{
public class C { }
public struct S { }
public enum E { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (16,13): warning CS0184: The given expression is never of the provided ('Outer<long>.C') type
// b = c2 is Outer<long>.C; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "c2 is Outer<long>.C").WithArguments("Outer<long>.C").WithLocation(16, 13),
// (18,13): warning CS0183: The given expression is always of the provided ('Outer<T>.S') type
// b = s1 is Outer<T>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s1 is Outer<T>.S").WithArguments("Outer<T>.S").WithLocation(18, 13),
// (23,13): warning CS0183: The given expression is always of the provided ('Outer<int>.S') type
// b = s2 is Outer<int>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s2 is Outer<int>.S").WithArguments("Outer<int>.S").WithLocation(23, 13),
// (24,13): warning CS0184: The given expression is never of the provided ('Outer<long>.S') type
// b = s2 is Outer<long>.S; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "s2 is Outer<long>.S").WithArguments("Outer<long>.S").WithLocation(24, 13),
// (26,13): warning CS0183: The given expression is always of the provided ('Outer<T>.E') type
// b = e1 is Outer<T>.E; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Outer<T>.E").WithArguments("Outer<T>.E").WithLocation(26, 13),
// (31,13): warning CS0183: The given expression is always of the provided ('Outer<int>.E') type
// b = e2 is Outer<int>.E; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Outer<int>.E").WithArguments("Outer<int>.E").WithLocation(31, 13),
// (32,13): warning CS0184: The given expression is never of the provided ('Outer<long>.E') type
// b = e2 is Outer<long>.E; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "e2 is Outer<long>.E").WithArguments("Outer<long>.E").WithLocation(32, 13));
}
[Fact]
public void TestIsOperatorWithGenericClassAndValueType()
{
var source = @"
class Program
{
static bool Goo<T>(C<T> c)
{
return c is int; // always false
}
}
class C<T> { }
";
CreateCompilation(source).VerifyDiagnostics(
// (6,16): warning CS0184: The given expression is never of the provided ('int') type
// return c is int; // always false
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "c is int").WithArguments("int").WithLocation(6, 16)
);
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithTypesThatCannotUnify()
{
var source = @"
class Program
{
static void Goo<T>(Outer<T>.S s1, Outer<T[]>.S s2)
{
bool b;
b = s1 is Outer<int[]>.S; // T -> int[]
b = s1 is Outer<T[]>.S; // Cannot unify - as in dev12, we do not warn.
b = s2 is Outer<int[]>.S; // T -> int
b = s2 is Outer<T[]>.S; // Always true.
b = s2 is Outer<T[,]>.S; // Cannot unify - as in dev12, we do not warn.
}
}
class Outer<T>
{
public struct S { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (11,13): warning CS0183: The given expression is always of the provided ('Outer<T[]>.S') type
// b = s2 is Outer<T[]>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s2 is Outer<T[]>.S").WithArguments("Outer<T[]>.S").WithLocation(11, 13));
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithSpecialTypes()
{
var source = @"
using System;
class Program
{
static void Goo<T, TClass, TStruct>(Outer<T>.E e1, Outer<int>.E e2, int i, T t, TClass tc, TStruct ts)
where TClass : class
where TStruct : struct
{
bool b;
b = e1 is Enum; // Always true.
b = e2 is Enum; // Always true.
b = 0 is Enum; // Always false.
b = i is Enum; // Always false.
b = t is Enum; // Deferred.
b = tc is Enum; // Deferred.
b = ts is Enum; // Deferred.
b = e1 is ValueType; // Always true.
b = e2 is ValueType; // Always true.
b = 0 is ValueType; // Always true.
b = i is ValueType; // Always true.
b = t is ValueType; // Deferred - null check.
b = tc is ValueType; // Deferred - null check.
b = ts is ValueType; // Always true.
b = e1 is Object; // Always true.
b = e2 is Object; // Always true.
b = 0 is Object; // Always true.
b = i is Object; // Always true.
b = t is Object; // Deferred - null check.
b = tc is Object; // Deferred - null check.
b = ts is Object; // Always true.
}
}
class Outer<T>
{
public enum E { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (11,13): warning CS0183: The given expression is always of the provided ('System.Enum') type
// b = e1 is Enum; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Enum").WithArguments("System.Enum").WithLocation(11, 13),
// (12,13): warning CS0183: The given expression is always of the provided ('System.Enum') type
// b = e2 is Enum; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Enum").WithArguments("System.Enum").WithLocation(12, 13),
// (13,13): warning CS0184: The given expression is never of the provided ('System.Enum') type
// b = 0 is Enum; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "0 is Enum").WithArguments("System.Enum").WithLocation(13, 13),
// (14,13): warning CS0184: The given expression is never of the provided ('System.Enum') type
// b = i is Enum; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "i is Enum").WithArguments("System.Enum").WithLocation(14, 13),
// (19,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = e1 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is ValueType").WithArguments("System.ValueType").WithLocation(19, 13),
// (20,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = e2 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is ValueType").WithArguments("System.ValueType").WithLocation(20, 13),
// (21,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = 0 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "0 is ValueType").WithArguments("System.ValueType").WithLocation(21, 13),
// (22,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = i is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "i is ValueType").WithArguments("System.ValueType").WithLocation(22, 13),
// (25,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = ts is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "ts is ValueType").WithArguments("System.ValueType").WithLocation(25, 13),
// (27,13): warning CS0183: The given expression is always of the provided ('object') type
// b = e1 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Object").WithArguments("object").WithLocation(27, 13),
// (28,13): warning CS0183: The given expression is always of the provided ('object') type
// b = e2 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Object").WithArguments("object").WithLocation(28, 13),
// (29,13): warning CS0183: The given expression is always of the provided ('object') type
// b = 0 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "0 is Object").WithArguments("object").WithLocation(29, 13),
// (30,13): warning CS0183: The given expression is always of the provided ('object') type
// b = i is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "i is Object").WithArguments("object").WithLocation(30, 13),
// (33,13): warning CS0183: The given expression is always of the provided ('object') type
// b = ts is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "ts is Object").WithArguments("object").WithLocation(33, 13));
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294"), WorkItem(546655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546655")]
[Fact()]
public void TestAsOperator_SpecErrorCase()
{
// SPEC: Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:
// SPEC: - An identity (�6.1.1), implicit nullable (�6.1.4), implicit reference (�6.1.6), boxing (�6.1.7),
// SPEC: explicit nullable (�6.2.3), explicit reference (�6.2.4), or unboxing (�6.2.5) conversion exists
// SPEC: from E to T.
// SPEC: - The type of E or T is an open type.
// SPEC: - E is the null literal.
// SPEC VIOLATION: The specification contains an error in the list of legal conversions above.
// SPEC VIOLATION: If we have "class C<T, U> where T : U where U : class" then there is
// SPEC VIOLATION: an implicit conversion from T to U, but it is not an identity, reference or
// SPEC VIOLATION: boxing conversion. It will be one of those at runtime, but at compile time
// SPEC VIOLATION: we do not know which, and therefore cannot classify it as any of those.
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action, Action>(null);
}
static U Goo<T, U>(T t)
where T : U
where U : class
{
var s = t is U;
return t as U;
}
}
";
CompileAndVerify(source, expectedOutput: "").VerifyDiagnostics();
}
[WorkItem(546655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546655")]
[Fact()]
public void TestIsOperatorWithTypeParameter_Bug16461()
{
var source = @"
using System;
public class G<T>
{
public bool M(T t) { return t is object; }
}
public class GG<T, V> where T : V
{
public bool M(T t) { return t is V; }
}
class Test
{
static void Main()
{
var obj = new G<Test>();
Console.WriteLine(obj.M( (Test)null ));
var obj1 = new GG<Test, Test>();
Console.WriteLine(obj1.M( (Test)null ));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
False");
comp.VerifyDiagnostics();
}
[Fact()]
public void TestIsAsOperator_UserDefinedConversionsNotAllowed()
{
var source = @"
// conversion.cs
class Goo { public Goo(Bar b){} }
class Goo2 { public Goo2(Bar b){} }
struct Bar
{
// Declare an implicit conversion from a int to a Bar
static public implicit operator Bar(int value)
{
return new Bar();
}
// Declare an explicit conversion from a Bar to Goo
static public explicit operator Goo(Bar value)
{
return new Goo(value);
}
// Declare an implicit conversion from a Bar to Goo2
static public implicit operator Goo2(Bar value)
{
return new Goo2(value);
}
}
class Test
{
static public void Main()
{
Bar numeral;
numeral = 10;
object a1 = numeral as Goo;
object a2 = 1 as Bar;
object a3 = numeral as Goo2;
bool b1 = numeral is Goo;
bool b2 = 1 is Bar;
bool b3 = numeral is Goo2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (37,21): error CS0039: Cannot convert type 'Bar' to 'Goo' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object a1 = numeral as Goo;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "numeral as Goo").WithArguments("Bar", "Goo"),
// (38,21): error CS0077: The as operator must be used with a reference type or nullable type ('Bar' is a non-nullable value type)
// object a2 = 1 as Bar;
Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "1 as Bar").WithArguments("Bar"),
// (39,21): error CS0039: Cannot convert type 'Bar' to 'Goo2' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object a3 = numeral as Goo2;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "numeral as Goo2").WithArguments("Bar", "Goo2"),
// (41,19): warning CS0184: The given expression is never of the provided ('Goo') type
// bool b1 = numeral is Goo;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "numeral is Goo").WithArguments("Goo"),
// (42,19): warning CS0184: The given expression is never of the provided ('Bar') type
// bool b2 = 1 is Bar;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is Bar").WithArguments("Bar"),
// (43,19): warning CS0184: The given expression is never of the provided ('Goo2') type
// bool b3 = numeral is Goo2;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "numeral is Goo2").WithArguments("Goo2"));
}
[WorkItem(543455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543455")]
[Fact()]
public void CS0184WRN_IsAlwaysFalse_Generic()
{
var text = @"
public class GenC<T> : GenI<T> where T : struct
{
public bool Test(T t)
{
return (t is C);
}
}
public interface GenI<T>
{
bool Test(T t);
}
public class C
{
public void Method() { }
public static int Main()
{
return 0;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is C").WithArguments("C"));
}
[WorkItem(547011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547011")]
[Fact()]
public void CS0184WRN_IsAlwaysFalse_IntPtr()
{
var text = @"using System;
public enum E
{
First
}
public class Base
{
public static void Main()
{
E e = E.First;
Console.WriteLine(e is IntPtr);
Console.WriteLine(e as IntPtr);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (12,27): warning CS0184: The given expression is never of the provided ('System.IntPtr') type
// Console.WriteLine(e is IntPtr);
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "e is IntPtr").WithArguments("System.IntPtr"),
// (13,27): error CS0077: The as operator must be used with a reference type or nullable type ('System.IntPtr' is a non-nullable value type)
// Console.WriteLine(e as IntPtr);
Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "e as IntPtr").WithArguments("System.IntPtr"));
}
[WorkItem(543443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543443")]
[Fact]
public void ParamsOperators()
{
var text =
@"class X
{
public static bool operator >(X a, params int[] b)
{
return true;
}
public static bool operator <(X a, params int[] b)
{
return false;
}
}";
CreateCompilation(text).VerifyDiagnostics(
// (3,39): error CS1670: params is not valid in this context public static bool operator >(X a, params int[] b)
Diagnostic(ErrorCode.ERR_IllegalParams, "params"),
// (8,40): error CS1670: params is not valid in this context
// public static bool operator <(X a, params int[] b)
Diagnostic(ErrorCode.ERR_IllegalParams, "params")
);
}
[WorkItem(543438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543438")]
[Fact()]
public void TestNullCoalesce_UserDefinedConversions()
{
var text =
@"class B
{
static void Main()
{
A a = null;
B b = null;
var c = a ?? b;
}
}
class A
{
public static implicit operator B(A x)
{
return new B();
}
}";
CompileAndVerify(text);
}
[WorkItem(543503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543503")]
[Fact()]
public void TestAsOperator_UserDefinedConversions()
{
var text =
@"using System;
class C<T>
{
public static implicit operator string (C<T> x)
{
return """";
}
string s = new C<T>() as string;
}";
CompileAndVerify(text);
}
[WorkItem(543503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543503")]
[Fact()]
public void TestIsOperator_UserDefinedConversions()
{
var text =
@"using System;
class C<T>
{
public static implicit operator string (C<T> x)
{
return """";
}
bool b = new C<T>() is string;
}";
CompileAndVerify(text);
}
[WorkItem(543483, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543483")]
[Fact]
public void TestEqualityOperator_NullableStructs()
{
string source1 =
@"
public struct NonGenericStruct { }
public struct GenericStruct<T> { }
public class Goo
{
public NonGenericStruct? ngsq;
public GenericStruct<int>? gsiq;
}
public class GenGoo<T>
{
public GenericStruct<T>? gstq;
}
public class Test
{
public static bool Run()
{
Goo f = new Goo();
f.ngsq = new NonGenericStruct();
f.gsiq = new GenericStruct<int>();
GenGoo<int> gf = new GenGoo<int>();
gf.gstq = new GenericStruct<int>();
return (f.ngsq != null) && (f.gsiq != null) && (gf.gstq != null);
}
public static void Main()
{
System.Console.WriteLine(Run() ? 1 : 0);
}
}";
string source2 = @"
struct S
{
public static bool operator ==(S? x, decimal? y) { return false; }
public static bool operator !=(S? x, decimal? y) { return false; }
public static bool operator ==(S? x, double? y) { return false; }
public static bool operator !=(S? x, double? y) { return false; }
public override int GetHashCode() { return 0; }
public override bool Equals(object x) { return false; }
static void Main()
{
S? s = default(S?);
// This is *not* equivalent to !s.HasValue because
// there is an applicable user-defined conversion.
// Even though the conversion is ambiguous!
if (s == null) s = default(S);
}
}
";
CompileAndVerify(source1, expectedOutput: "1");
CreateCompilation(source2).VerifyDiagnostics(
// (16,9): error CS0034: Operator '==' is ambiguous on operands of type 'S?' and '<null>'
// if (s == null) s = default(S);
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "s == null").WithArguments("==", "S?", "<null>"));
}
[WorkItem(543432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543432")]
[Fact]
public void NoNewForOperators()
{
var text =
@"class A
{
public static implicit operator A(D x)
{
return null;
}
}
class B : A
{
public static implicit operator B(D x)
{
return null;
}
}
class D {}";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact(), WorkItem(543433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543433")]
public void ERR_NoImplicitConvCast_UserDefinedConversions()
{
var text =
@"class A
{
public static A operator ++(A x)
{
return new A();
}
}
class B : A
{
static void Main()
{
B b = new B();
b++;
}
}
";
CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b++").WithArguments("A", "B"));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorIncrement()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static (T1 fst, T2 snd) operator ++((T1 one, T2 two) tuple)
{
return tuple;
}
}
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorConvert()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static explicit operator (T1 fst, T2 snd)((T1 one, T2 two) s)
{
return s;
}
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,41): error CS0555: User-defined operator cannot convert a type to itself
// public static explicit operator (T1 fst, T2 snd)((T1 one, T2 two) s)
Diagnostic(ErrorCode.ERR_IdentityConversion, "(T1 fst, T2 snd)").WithLocation(6, 41));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorConvertToBaseType()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static explicit operator ValueType(ValueTuple<T1, T2> s)
{
return s;
}
}
}
";
CreateCompilation(text).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(
// (6,41): error CS0553: '(T1, T2).explicit operator ValueType((T1, T2))': user-defined conversions to or from a base type are not allowed
// public static explicit operator ValueType(ValueTuple<T1, T2> s)
Diagnostic(ErrorCode.ERR_ConversionWithBase, "ValueType").WithArguments("(T1, T2).explicit operator System.ValueType((T1, T2))").WithLocation(6, 41));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleBinaryOperator()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static ValueTuple<T1, T2> operator +((T1 fst, T2 snd) s1, (T1 one, T2 two) s2)
{
return s1;
}
}
}
";
CreateCompilation(text).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_01()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
string expectedOutput = @"True
False";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_02()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((Func<int>)(C)null == (D)null);
Console.WriteLine((Func<int>)(C)null == (Action)(D)null);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (21,27): error CS0019: Operator '==' cannot be applied to operands of type 'System.Func<int>' and 'D'
// Console.WriteLine((Func<int>)(C)null == (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(Func<int>)(C)null == (D)null").WithArguments("==", "System.Func<int>", "D"),
// (22,27): error CS0019: Operator '==' cannot be applied to operands of type 'System.Func<int>' and 'System.Action'
// Console.WriteLine((Func<int>)(C)null == (Action)(D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(Func<int>)(C)null == (Action)(D)null").WithArguments("==", "System.Func<int>", "System.Action"));
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_03_Ambiguous()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
public static implicit operator Func<int>(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (26,27): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'D'
// Console.WriteLine((C)null == (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(C)null == (D)null").WithArguments("==", "C", "D"),
// (27,27): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'D'
// Console.WriteLine((C)null != (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(C)null != (D)null").WithArguments("!=", "C", "D"));
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_04_BaseTypes()
{
string source =
@"
using System;
class A
{
public static implicit operator Func<int>(A x)
{
return null;
}
}
class C : A
{
}
class D
{
public static implicit operator Func<int>(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
string expectedOutput = @"True
False";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[WorkItem(543754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543754")]
[Fact]
public void TestEqualityOperator_NullableDecimal()
{
string source =
@"
public class Test
{
public static bool Goo(decimal? deq)
{
return deq == null;
}
public static void Main()
{
Goo(null);
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[WorkItem(543910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543910")]
[Fact]
public void TypeParameterConstraintToGenericType()
{
string source =
@"
public class Gen<T>
{
public T t;
public Gen(T t)
{
this.t = t;
}
public static Gen<T> operator + (Gen<T> x, T y)
{
return new Gen<T>(y);
}
}
public class ConstrainedTestContext<T,U> where T : Gen<U>
{
public static Gen<U> ExecuteOpAddition(T x, U y)
{
return x + y;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(544490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544490")]
[Fact]
public void LiftedUserDefinedUnaryOperator()
{
string source =
@"
struct S
{
public static int operator +(S s) { return 1; }
public static void Main()
{
S s = new S();
S? sq = s;
var j = +sq;
System.Console.WriteLine(j);
}
}
";
CompileAndVerify(source, expectedOutput: "1");
}
[WorkItem(544490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544490")]
[Fact]
public void TestDefaultOperatorEnumConstantValue()
{
string source =
@"
enum X { F = 0 };
class C
{
public static int Main()
{
const X x = default(X);
return (int)x;
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[Fact]
public void OperatorHiding1()
{
string source = @"
class Base1
{
public static Base1 operator +(Base1 b, Derived1 d) { return b; }
}
class Derived1 : Base1
{
public static Base1 operator +(Base1 b, Derived1 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding2()
{
string source = @"
class Base2
{
public static Base2 op_Addition(Base2 b, Derived2 d) { return b; }
}
class Derived2 : Base2
{
public static Base2 operator +(Base2 b, Derived2 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding3()
{
string source = @"
class Base3
{
public static Base3 operator +(Base3 b, Derived3 d) { return b; }
}
class Derived3 : Base3
{
public static Base3 op_Addition(Base3 b, Derived3 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding4()
{
string source = @"
class Base4
{
public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
}
class Derived4 : Base4
{
public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,25): warning CS0108: 'Derived4.op_Addition(Base4, Derived4)' hides inherited member 'Base4.op_Addition(Base4, Derived4)'. Use the new keyword if hiding was intended.
// public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
Diagnostic(ErrorCode.WRN_NewRequired, "op_Addition").WithArguments("Derived4.op_Addition(Base4, Derived4)", "Base4.op_Addition(Base4, Derived4)"));
}
[Fact]
public void ConversionHiding1()
{
string source = @"
class Base1
{
public static implicit operator string(Base1 b) { return null; }
}
class Derived1 : Base1
{
public static implicit operator string(Base1 b) { return null; } // CS0556, but not CS0108
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,37): error CS0556: User-defined conversion must convert to or from the enclosing type
// public static implicit operator string(Base1 b) { return null; }
Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "string"));
}
[Fact]
public void ConversionHiding2()
{
string source = @"
class Base2
{
public static string op_Explicit(Derived2 d) { return null; }
}
class Derived2 : Base2
{
public static implicit operator string(Derived2 d) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ConversionHiding3()
{
string source = @"
class Base3
{
public static implicit operator string(Base3 b) { return null; }
}
class Derived3 : Base3
{
public static string op_Explicit(Base3 b) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ConversionHiding4()
{
string source = @"
class Base4
{
public static string op_Explicit(Base4 b) { return null; }
}
class Derived4 : Base4
{
public static string op_Explicit(Base4 b) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,26): warning CS0108: 'Derived4.op_Explicit(Base4)' hides inherited member 'Base4.op_Explicit(Base4)'. Use the new keyword if hiding was intended.
// public static string op_Explicit(Base4 b) { return null; }
Diagnostic(ErrorCode.WRN_NewRequired, "op_Explicit").WithArguments("Derived4.op_Explicit(Base4)", "Base4.op_Explicit(Base4)"));
}
[Fact]
public void ClassesWithOperatorNames()
{
string source = @"
class op_Increment
{
public static op_Increment operator ++ (op_Increment c) { return null; }
}
class op_Decrement
{
public static op_Decrement operator -- (op_Decrement c) { return null; }
}
class op_UnaryPlus
{
public static int operator + (op_UnaryPlus c) { return 0; }
}
class op_UnaryNegation
{
public static int operator - (op_UnaryNegation c) { return 0; }
}
class op_OnesComplement
{
public static int operator ~ (op_OnesComplement c) { return 0; }
}
class op_Addition
{
public static int operator + (op_Addition c, int i) { return 0; }
}
class op_Subtraction
{
public static int operator - (op_Subtraction c, int i) { return 0; }
}
class op_Multiply
{
public static int operator * (op_Multiply c, int i) { return 0; }
}
class op_Division
{
public static int operator / (op_Division c, int i) { return 0; }
}
class op_Modulus
{
public static int operator % (op_Modulus c, int i) { return 0; }
}
class op_ExclusiveOr
{
public static int operator ^ (op_ExclusiveOr c, int i) { return 0; }
}
class op_BitwiseAnd
{
public static int operator & (op_BitwiseAnd c, int i) { return 0; }
}
class op_BitwiseOr
{
public static int operator | (op_BitwiseOr c, int i) { return 0; }
}
class op_LeftShift
{
public static long operator << (op_LeftShift c, int i) { return 0; }
}
class op_RightShift
{
public static long operator >> (op_RightShift c, int i) { return 0; }
}
class op_UnsignedRightShift
{
}
";
CreateCompilation(source).VerifyDiagnostics(
// (4,38): error CS0542: 'op_Increment': member names cannot be the same as their enclosing type
// public static op_Increment operator ++ (op_Increment c) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "++").WithArguments("op_Increment"),
// (8,38): error CS0542: 'op_Decrement': member names cannot be the same as their enclosing type
// public static op_Decrement operator -- (op_Decrement c) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "--").WithArguments("op_Decrement"),
// (12,29): error CS0542: 'op_UnaryPlus': member names cannot be the same as their enclosing type
// public static int operator + (op_UnaryPlus c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "+").WithArguments("op_UnaryPlus"),
// (16,39): error CS0542: 'op_UnaryNegation': member names cannot be the same as their enclosing type
// public static int operator - (op_UnaryNegation c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "-").WithArguments("op_UnaryNegation"),
// (20,29): error CS0542: 'op_OnesComplement': member names cannot be the same as their enclosing type
// public static int operator ~ (op_OnesComplement c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "~").WithArguments("op_OnesComplement"),
// (24,29): error CS0542: 'op_Addition': member names cannot be the same as their enclosing type
// public static int operator + (op_Addition c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "+").WithArguments("op_Addition"),
// (28,29): error CS0542: 'op_Subtraction': member names cannot be the same as their enclosing type
// public static int operator - (op_Subtraction c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "-").WithArguments("op_Subtraction"),
// (32,29): error CS0542: 'op_Multiply': member names cannot be the same as their enclosing type
// public static int operator * (op_Multiply c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "*").WithArguments("op_Multiply"),
// (36,29): error CS0542: 'op_Division': member names cannot be the same as their enclosing type
// public static int operator / (op_Division c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "/").WithArguments("op_Division"),
// (40,29): error CS0542: 'op_Modulus': member names cannot be the same as their enclosing type
// public static int operator % (op_Modulus c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "%").WithArguments("op_Modulus"),
// (44,29): error CS0542: 'op_ExclusiveOr': member names cannot be the same as their enclosing type
// public static int operator ^ (op_ExclusiveOr c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "^").WithArguments("op_ExclusiveOr"),
// (48,29): error CS0542: 'op_BitwiseAnd': member names cannot be the same as their enclosing type
// public static int operator & (op_BitwiseAnd c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "&").WithArguments("op_BitwiseAnd"),
// (52,29): error CS0542: 'op_BitwiseOr': member names cannot be the same as their enclosing type
// public static int operator | (op_BitwiseOr c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "|").WithArguments("op_BitwiseOr"),
// (56,30): error CS0542: 'op_LeftShift': member names cannot be the same as their enclosing type
// public static long operator << (op_LeftShift c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "<<").WithArguments("op_LeftShift"),
// (60,30): error CS0542: 'op_RightShift': member names cannot be the same as their enclosing type
// public static long operator >> (op_RightShift c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, ">>").WithArguments("op_RightShift"));
}
[Fact]
public void ClassesWithConversionNames()
{
string source = @"
class op_Explicit
{
public static explicit operator op_Explicit(int x) { return null; }
}
class op_Implicit
{
public static implicit operator op_Implicit(int x) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (4,37): error CS0542: 'op_Explicit': member names cannot be the same as their enclosing type
// public static explicit operator op_Explicit(int x) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "op_Explicit").WithArguments("op_Explicit"),
// (9,37): error CS0542: 'op_Implicit': member names cannot be the same as their enclosing type
// public static implicit operator op_Implicit(int x) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "op_Implicit").WithArguments("op_Implicit"));
}
[Fact, WorkItem(546771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546771")]
public void TestIsNullable_Bug16777()
{
string source = @"
class Program
{
enum E { }
static void Main()
{
M(null);
M(0);
}
static void M(E? e)
{
System.Console.Write(e is E ? 't' : 'f');
}
}
";
CompileAndVerify(source: source, expectedOutput: "ft");
}
[Fact]
public void CompoundOperatorWithThisOnLeft()
{
string source =
@"using System;
public struct Value
{
int value;
public Value(int value)
{
this.value = value;
}
public static Value operator +(Value a, int b)
{
return new Value(a.value + b);
}
public void Test()
{
this += 2;
}
public void Print()
{
Console.WriteLine(this.value);
}
public static void Main(string[] args)
{
Value v = new Value(1);
v.Test();
v.Print();
}
}";
string output = @"3";
CompileAndVerify(source: source, expectedOutput: output);
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality1()
{
string source = @"
struct S1
{
// Interesting
public static bool operator ==(S1 x, S1 y) { throw null; }
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S1 y) { throw null; }
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1)
{
return s1 == null;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var expectedOperator = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("S1").GetMembers(WellKnownMemberNames.EqualityOperatorName).
OfType<MethodSymbol>().Single(m => m.ParameterTypesWithAnnotations[0].Equals(m.ParameterTypesWithAnnotations[1], TypeCompareKind.ConsiderEverything));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
var info = model.GetSymbolInfo(syntax);
Assert.Equal(expectedOperator.GetPublicSymbol(), info.Symbol);
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality2()
{
string source = @"
using System;
struct S1
{
// Interesting
[Obsolete(""A"")]
public static bool operator ==(S1 x, S1 y) { throw null; }
[Obsolete(""B"")]
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S1 y) { throw null; }
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1)
{
return s1 == null;
}
}
";
// CONSIDER: This is a little silly, since that method will never be called.
CreateCompilation(source).VerifyDiagnostics(
// (27,16): warning CS0618: 'S1.operator ==(S1, S1)' is obsolete: 'A'
// return s1 == null;
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "s1 == null").WithArguments("S1.operator ==(S1, S1)", "A"));
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality3()
{
string source = @"
struct S1
{
// Interesting
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1, S2? s2)
{
return s1 == s2;
}
}
";
// CONSIDER: There is no reason not to allow this, but dev11 doesn't.
CreateCompilation(source).VerifyDiagnostics(
// (21,16): error CS0019: Operator '==' cannot be applied to operands of type 'S1?' and 'S2?'
// return s1 == s2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 == s2").WithArguments("==", "S1?", "S2?"));
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void AmbiguousLogicalOrConversion()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
// SPEC VIOLATION: According to the spec, this is ambiguous. However, we will match the dev11 behavior.
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("i2", syntax.Identifier.ValueText);
var info = model.GetTypeInfo(syntax);
Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("InputParameter"), info.Type.GetSymbol());
Assert.Equal(comp.GetSpecialType(SpecialType.System_Boolean), info.ConvertedType.GetSymbol());
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void AmbiguousOrConversion()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 | i2;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (21,18): error CS0034: Operator '|' is ambiguous on operands of type 'InputParameter' and 'InputParameter'
// bool b = i1 | i2;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i1 | i2").WithArguments("|", "InputParameter", "InputParameter"));
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void DynamicAmbiguousLogicalOrConversion()
{
string source = @"
using System;
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
System.Console.WriteLine(""A"");
return true;
}
public static implicit operator int(InputParameter inputParameter)
{
System.Console.WriteLine(""B"");
return 1;
}
}
class Program
{
static void Main(string[] args)
{
dynamic i1 = new InputParameter();
dynamic i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: @"A
A");
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[ConditionalFact(typeof(DesktopOnly))]
public void DynamicAmbiguousOrConversion()
{
string source = @"
using System;
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
System.Console.WriteLine(""A"");
return true;
}
public static implicit operator int(InputParameter inputParameter)
{
System.Console.WriteLine(""B"");
return 1;
}
}
class Program
{
static void Main(string[] args)
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
dynamic i1 = new InputParameter();
dynamic i2 = new InputParameter();
bool b = i1 | i2;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.ReleaseExe);
CompileAndVerifyException<Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>(comp,
"Operator '|' is ambiguous on operands of type 'InputParameter' and 'InputParameter'");
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void UnambiguousLogicalOrConversion1()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("i2", syntax.Identifier.ValueText);
var info = model.GetTypeInfo(syntax);
Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("InputParameter").GetPublicSymbol(), info.Type);
Assert.Equal(comp.GetSpecialType(SpecialType.System_Boolean).GetPublicSymbol(), info.ConvertedType);
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void UnambiguousLogicalOrConversion2()
{
string source = @"
class InputParameter
{
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (16,18): error CS0019: Operator '||' cannot be applied to operands of type 'InputParameter' and 'InputParameter'
// bool b = i1 || i2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i1 || i2").WithArguments("||", "InputParameter", "InputParameter"));
}
[WorkItem(665002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665002")]
[Fact]
public void DedupingLiftedUserDefinedOperators()
{
string source = @"
using System;
public class RubyTime
{
public static TimeSpan operator -(RubyTime x, DateTime y)
{
throw null;
}
public static TimeSpan operator -(RubyTime x, RubyTime y)
{
throw null;
}
public static implicit operator DateTime(RubyTime time)
{
throw null;
}
TimeSpan Test(RubyTime x, DateTime y)
{
return x - y;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
/// <summary>
/// Verify operators returned from BinaryOperatorEasyOut match
/// the operators found from overload resolution.
/// </summary>
[Fact]
public void BinaryOperators_EasyOut()
{
var source =
@"class Program
{
static T F<T>() => throw null;
static void Main()
{
F<object>();
F<string>();
F<bool>();
F<char>();
F<sbyte>();
F<short>();
F<int>();
F<long>();
F<byte>();
F<ushort>();
F<uint>();
F<ulong>();
F<nint>();
F<nuint>();
F<float>();
F<double>();
F<decimal>();
F<bool?>();
F<char?>();
F<sbyte?>();
F<short?>();
F<int?>();
F<long?>();
F<byte?>();
F<ushort?>();
F<uint?>();
F<ulong?>();
F<nint?>();
F<nuint?>();
F<float?>();
F<double?>();
F<decimal?>();
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var syntax = tree.GetRoot();
var methodBody = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Last().Body;
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(methodBody.SpanStart);
var diagnostics = DiagnosticBag.GetInstance();
var block = binder.BindEmbeddedBlock(methodBody, diagnostics);
diagnostics.Free();
var exprs = block.Statements.SelectAsArray(stmt => ((BoundExpressionStatement)stmt).Expression);
Assert.Equal(32, exprs.Length);
var operators = new[]
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Equal,
BinaryOperatorKind.NotEqual,
BinaryOperatorKind.Or,
BinaryOperatorKind.And,
BinaryOperatorKind.Xor,
};
foreach (var op in operators)
{
foreach (var left in exprs)
{
foreach (var right in exprs)
{
var signature1 = getBinaryOperator(binder, op, left, right, useEasyOut: true);
var signature2 = getBinaryOperator(binder, op, left, right, useEasyOut: false);
Assert.Equal(signature1, signature2);
}
}
}
static BinaryOperatorKind getBinaryOperator(Binder binder, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, bool useEasyOut)
{
var overloadResolution = new OverloadResolution(binder);
var result = BinaryOperatorOverloadResolutionResult.GetInstance();
if (useEasyOut)
{
overloadResolution.BinaryOperatorOverloadResolution_EasyOut(kind, left, right, result);
}
else
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
overloadResolution.BinaryOperatorOverloadResolution_NoEasyOut(kind, left, right, result, ref discardedUseSiteInfo);
}
var signature = result.Best.Signature.Kind;
result.Free();
return signature;
}
}
[Fact()]
public void UnaryIntrinsicSymbols1()
{
UnaryOperatorKind[] operators =
{
UnaryOperatorKind.PostfixIncrement,
UnaryOperatorKind.PostfixDecrement,
UnaryOperatorKind.PrefixIncrement,
UnaryOperatorKind.PrefixDecrement,
UnaryOperatorKind.UnaryPlus,
UnaryOperatorKind.UnaryMinus,
UnaryOperatorKind.LogicalNegation,
UnaryOperatorKind.BitwiseComplement
};
string[] opTokens = {"++","--","++","--",
"+","-","!","~"};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"dynamic",
"byte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{1}({0} x1, System.Nullable<{0}> x2)\n", arg1, n);
builder.Append(
"{\n");
for (int k = 0; k < operators.Length; k++)
{
if (operators[k] == UnaryOperatorKind.PostfixDecrement || operators[k] == UnaryOperatorKind.PostfixIncrement)
{
builder.AppendFormat(
" var z{0}_1 = x1 {1};\n" +
" var z{0}_2 = x2 {1};\n" +
" if (x1 {1}) {{}}\n" +
" if (x2 {1}) {{}}\n",
k, opTokens[k]);
}
else
{
builder.AppendFormat(
" var z{0}_1 = {1} x1;\n" +
" var z{0}_2 = {1} x2;\n" +
" if ({1} x1) {{}}\n" +
" if ({1} x2) {{}}\n",
k, opTokens[k]);
}
}
builder.Append(
"}\n");
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select ((ExpressionSyntax)(node as PrefixUnaryExpressionSyntax)) ?? node as PostfixUnaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
n = 0;
for (int name = 0; name < typeNames.Length; name++)
{
TypeSymbol type;
if (name == typeNames.Length - 1)
{
type = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
}
else if (name == typeNames.Length - 2)
{
type = compilation.DynamicType;
}
else
{
type = compilation.GetTypeByMetadataName(typeNames[name]);
}
foreach (var op in operators)
{
TestUnaryIntrinsicSymbol(
op,
type,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3]);
n += 4;
}
}
Assert.Equal(n, nodes.Length);
}
private void TestUnaryIntrinsicSymbol(
UnaryOperatorKind op,
TypeSymbol type,
CSharpCompilation compilation,
SemanticModel semanticModel,
ExpressionSyntax node1,
ExpressionSyntax node2,
ExpressionSyntax node3,
ExpressionSyntax node4
)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
Assert.Equal(type.IsDynamic() ? CandidateReason.LateBound : CandidateReason.None, info1.CandidateReason);
Assert.Equal(0, info1.CandidateSymbols.Length);
var symbol1 = (IMethodSymbol)info1.Symbol;
var symbol2 = semanticModel.GetSymbolInfo(node2).Symbol;
var symbol3 = (IMethodSymbol)semanticModel.GetSymbolInfo(node3).Symbol;
var symbol4 = semanticModel.GetSymbolInfo(node4).Symbol;
Assert.Equal(symbol1, symbol3);
if ((object)symbol1 != null)
{
Assert.NotSame(symbol1, symbol3);
Assert.Equal(symbol1.GetHashCode(), symbol3.GetHashCode());
Assert.Equal(symbol1.Parameters[0], symbol3.Parameters[0]);
Assert.Equal(symbol1.Parameters[0].GetHashCode(), symbol3.Parameters[0].GetHashCode());
}
Assert.Equal(symbol2, symbol4);
TypeSymbol underlying = type;
if (op == UnaryOperatorKind.BitwiseComplement ||
op == UnaryOperatorKind.PrefixDecrement || op == UnaryOperatorKind.PrefixIncrement ||
op == UnaryOperatorKind.PostfixDecrement || op == UnaryOperatorKind.PostfixIncrement)
{
underlying = type.EnumUnderlyingTypeOrSelf();
}
UnaryOperatorKind result = OverloadResolution.UnopEasyOut.OpKind(op, underlying);
UnaryOperatorSignature signature;
if (result == UnaryOperatorKind.Error)
{
if (type.IsDynamic())
{
signature = new UnaryOperatorSignature(op | UnaryOperatorKind.Dynamic, type, type);
}
else if (type.IsPointerType() &&
(op == UnaryOperatorKind.PrefixDecrement || op == UnaryOperatorKind.PrefixIncrement ||
op == UnaryOperatorKind.PostfixDecrement || op == UnaryOperatorKind.PostfixIncrement))
{
signature = new UnaryOperatorSignature(op | UnaryOperatorKind.Pointer, type, type);
}
else
{
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
}
else
{
signature = compilation.builtInOperators.GetSignature(result);
if ((object)underlying != (object)type)
{
Assert.Equal(underlying, signature.OperandType);
Assert.Equal(underlying, signature.ReturnType);
signature = new UnaryOperatorSignature(signature.Kind, type, type);
}
}
Assert.NotNull(symbol1);
string containerName = signature.OperandType.ToTestDisplayString();
string returnName = signature.ReturnType.ToTestDisplayString();
if (op == UnaryOperatorKind.LogicalNegation && type.IsEnumType())
{
containerName = type.ToTestDisplayString();
returnName = containerName;
}
Assert.Equal(String.Format("{2} {0}.{1}({0} value)",
containerName,
OperatorFacts.UnaryOperatorNameFromOperatorKind(op),
returnName),
symbol1.ToTestDisplayString());
Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind);
Assert.True(symbol1.IsImplicitlyDeclared);
bool expectChecked = false;
switch (op)
{
case UnaryOperatorKind.UnaryMinus:
expectChecked = (type.IsDynamic() || symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType());
break;
case UnaryOperatorKind.PrefixDecrement:
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.PostfixIncrement:
expectChecked = (type.IsDynamic() || type.IsPointerType() ||
symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType() ||
symbol1.ContainingType.SpecialType == SpecialType.System_Char);
break;
default:
expectChecked = type.IsDynamic();
break;
}
Assert.Equal(expectChecked, symbol1.IsCheckedBuiltin);
Assert.False(symbol1.IsGenericMethod);
Assert.False(symbol1.IsExtensionMethod);
Assert.False(symbol1.IsExtern);
Assert.False(symbol1.CanBeReferencedByName);
Assert.Null(symbol1.GetSymbol().DeclaringCompilation);
Assert.Equal(symbol1.Name, symbol1.MetadataName);
Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters[0].Type);
Assert.Equal(0, symbol1.Locations.Length);
Assert.Null(symbol1.GetDocumentationCommentId());
Assert.Equal("", symbol1.GetDocumentationCommentXml());
Assert.True(symbol1.GetSymbol().HasSpecialName);
Assert.True(symbol1.IsStatic);
Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility);
Assert.False(symbol1.HidesBaseMethodsByName);
Assert.False(symbol1.IsOverride);
Assert.False(symbol1.IsVirtual);
Assert.False(symbol1.IsAbstract);
Assert.False(symbol1.IsSealed);
Assert.Equal(1, symbol1.GetSymbol().ParameterCount);
Assert.Equal(0, symbol1.Parameters[0].Ordinal);
var otherSymbol = (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol;
Assert.Equal(symbol1, otherSymbol);
if (type.IsValueType && !type.IsPointerType())
{
Assert.Equal(symbol1, symbol2);
return;
}
Assert.Null(symbol2);
}
[Fact]
[WorkItem(39975, "https://github.com/dotnet/roslyn/issues/39975")]
public void CheckedUnaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(int x)
{
var z1 = -x;
var z2 = --x;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select ((ExpressionSyntax)(node as PrefixUnaryExpressionSyntax)) ?? node as PostfixUnaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/mono/mono/issues/10917")]
public void BinaryIntrinsicSymbols1()
{
BinaryOperatorKind[] operators =
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.Equal,
BinaryOperatorKind.NotEqual,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Or,
BinaryOperatorKind.And,
BinaryOperatorKind.LogicalOr,
BinaryOperatorKind.LogicalAnd
};
string[] opTokens = {
"+",
"-",
"*",
"/",
"%",
"==",
"!=",
"<=",
">=",
"<",
">",
"<<",
">>",
"^",
"|",
"&",
"||",
"&&"};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"System.Delegate",
"System.Action",
"System.AppDomainInitializer",
"System.ValueType",
"TestStructure",
"Module1",
"dynamic",
"byte*",
"sbyte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"struct TestStructure\n" +
"{}\n" +
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
foreach (var arg2 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{2}({0} x1, {1} y1, System.Nullable<{0}> x2, System.Nullable<{1}> y2)\n" +
"{{\n", arg1, arg2, n);
for (int k = 0; k < opTokens.Length; k++)
{
builder.AppendFormat(
" var z{0}_1 = x1 {1} y1;\n" +
" var z{0}_2 = x2 {1} y2;\n" +
" var z{0}_3 = x2 {1} y1;\n" +
" var z{0}_4 = x1 {1} y2;\n" +
" if (x1 {1} y1) {{}}\n" +
" if (x2 {1} y2) {{}}\n" +
" if (x2 {1} y1) {{}}\n" +
" if (x1 {1} y2) {{}}\n",
k, opTokens[k]);
}
builder.Append(
"}\n");
}
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45Extended, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
TypeSymbol[] types = new TypeSymbol[typeNames.Length];
for (int i = 0; i < typeNames.Length - 3; i++)
{
types[i] = compilation.GetTypeByMetadataName(typeNames[i]);
}
Assert.Null(types[types.Length - 3]);
types[types.Length - 3] = compilation.DynamicType;
Assert.Null(types[types.Length - 2]);
types[types.Length - 2] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
Assert.Null(types[types.Length - 1]);
types[types.Length - 1] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_SByte));
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as BinaryExpressionSyntax)).
Where(node => (object)node != null).ToArray();
n = 0;
foreach (var leftType in types)
{
foreach (var rightType in types)
{
foreach (var op in operators)
{
TestBinaryIntrinsicSymbol(
op,
leftType,
rightType,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3],
nodes[n + 4],
nodes[n + 5],
nodes[n + 6],
nodes[n + 7]);
n += 8;
}
}
}
Assert.Equal(n, nodes.Length);
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(39975, "https://github.com/dotnet/roslyn/issues/39975")]
public void BinaryIntrinsicSymbols2()
{
BinaryOperatorKind[] operators =
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Or,
BinaryOperatorKind.And
};
string[] opTokens = {
"+=",
"-=",
"*=",
"/=",
"%=",
"<<=",
">>=",
"^=",
"|=",
"&="};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"System.Delegate",
"System.Action",
"System.AppDomainInitializer",
"System.ValueType",
"TestStructure",
"Module1",
"dynamic",
"byte*",
"sbyte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"struct TestStructure\n" +
"{}\n" +
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
foreach (var arg2 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{2}({0} x1, {1} y1, System.Nullable<{0}> x2, System.Nullable<{1}> y2)\n" +
"{{\n", arg1, arg2, n);
for (int k = 0; k < opTokens.Length; k++)
{
builder.AppendFormat(
" x1 {1} y1;\n" +
" x2 {1} y2;\n" +
" x2 {1} y1;\n" +
" x1 {1} y2;\n" +
" if (x1 {1} y1) {{}}\n" +
" if (x2 {1} y2) {{}}\n" +
" if (x2 {1} y1) {{}}\n" +
" if (x1 {1} y2) {{}}\n",
k, opTokens[k]);
}
builder.Append(
"}\n");
}
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40Extended, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
TypeSymbol[] types = new TypeSymbol[typeNames.Length];
for (int i = 0; i < typeNames.Length - 3; i++)
{
types[i] = compilation.GetTypeByMetadataName(typeNames[i]);
}
Assert.Null(types[types.Length - 3]);
types[types.Length - 3] = compilation.DynamicType;
Assert.Null(types[types.Length - 2]);
types[types.Length - 2] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
Assert.Null(types[types.Length - 1]);
types[types.Length - 1] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_SByte));
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as AssignmentExpressionSyntax)).
Where(node => (object)node != null).ToArray();
n = 0;
foreach (var leftType in types)
{
foreach (var rightType in types)
{
foreach (var op in operators)
{
TestBinaryIntrinsicSymbol(
op,
leftType,
rightType,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3],
nodes[n + 4],
nodes[n + 5],
nodes[n + 6],
nodes[n + 7]);
n += 8;
}
}
}
Assert.Equal(n, nodes.Length);
}
private void TestBinaryIntrinsicSymbol(
BinaryOperatorKind op,
TypeSymbol leftType,
TypeSymbol rightType,
CSharpCompilation compilation,
SemanticModel semanticModel,
ExpressionSyntax node1,
ExpressionSyntax node2,
ExpressionSyntax node3,
ExpressionSyntax node4,
ExpressionSyntax node5,
ExpressionSyntax node6,
ExpressionSyntax node7,
ExpressionSyntax node8
)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if (info1.Symbol == null)
{
if (info1.CandidateSymbols.Length == 0)
{
if (leftType.IsDynamic() || rightType.IsDynamic())
{
Assert.True(CandidateReason.LateBound == info1.CandidateReason || CandidateReason.None == info1.CandidateReason);
}
else
{
Assert.Equal(CandidateReason.None, info1.CandidateReason);
}
}
else
{
Assert.Equal(CandidateReason.OverloadResolutionFailure, info1.CandidateReason);
foreach (MethodSymbol s in info1.CandidateSymbols)
{
Assert.Equal(MethodKind.UserDefinedOperator, s.MethodKind);
}
}
}
else
{
Assert.Equal(leftType.IsDynamic() || rightType.IsDynamic() ? CandidateReason.LateBound : CandidateReason.None, info1.CandidateReason);
Assert.Equal(0, info1.CandidateSymbols.Length);
}
var symbol1 = (IMethodSymbol)info1.Symbol;
var symbol2 = semanticModel.GetSymbolInfo(node2).Symbol;
var symbol3 = semanticModel.GetSymbolInfo(node3).Symbol;
var symbol4 = semanticModel.GetSymbolInfo(node4).Symbol;
var symbol5 = (IMethodSymbol)semanticModel.GetSymbolInfo(node5).Symbol;
var symbol6 = semanticModel.GetSymbolInfo(node6).Symbol;
var symbol7 = semanticModel.GetSymbolInfo(node7).Symbol;
var symbol8 = semanticModel.GetSymbolInfo(node8).Symbol;
Assert.Equal(symbol1, symbol5);
Assert.Equal(symbol2, symbol6);
Assert.Equal(symbol3, symbol7);
Assert.Equal(symbol4, symbol8);
if ((object)symbol1 != null && symbol1.IsImplicitlyDeclared)
{
Assert.NotSame(symbol1, symbol5);
Assert.Equal(symbol1.GetHashCode(), symbol5.GetHashCode());
for (int i = 0; i < 2; i++)
{
Assert.Equal(symbol1.Parameters[i], symbol5.Parameters[i]);
Assert.Equal(symbol1.Parameters[i].GetHashCode(), symbol5.Parameters[i].GetHashCode());
}
Assert.NotEqual(symbol1.Parameters[0], symbol5.Parameters[1]);
}
switch (op)
{
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
BinaryOperatorKind result = OverloadResolution.BinopEasyOut.OpKind(op, leftType, rightType);
BinaryOperatorSignature signature;
bool isDynamic = (leftType.IsDynamic() || rightType.IsDynamic());
if (result == BinaryOperatorKind.Error)
{
if (leftType.IsDynamic() && !rightType.IsPointerType() && !rightType.IsRestrictedType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Dynamic, leftType, rightType, leftType);
}
else if (rightType.IsDynamic() && !leftType.IsPointerType() && !leftType.IsRestrictedType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Dynamic, leftType, rightType, rightType);
}
else if ((op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) &&
leftType.IsReferenceType && rightType.IsReferenceType &&
(TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2) || compilation.Conversions.ClassifyConversionFromType(leftType, rightType, ref useSiteDiagnostics).IsReference))
{
if (leftType.IsDelegateType() && rightType.IsDelegateType())
{
Assert.Equal(leftType, rightType);
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate,
leftType, // TODO: this feels like a spec violation
leftType, // TODO: this feels like a spec violation
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else if (leftType.SpecialType == SpecialType.System_Delegate && rightType.SpecialType == SpecialType.System_Delegate)
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate,
compilation.GetSpecialType(SpecialType.System_Delegate), compilation.GetSpecialType(SpecialType.System_Delegate),
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Object, compilation.ObjectType, compilation.ObjectType,
compilation.GetSpecialType(SpecialType.System_Boolean));
}
}
else if (op == BinaryOperatorKind.Addition &&
((leftType.IsStringType() && !rightType.IsPointerType()) || (!leftType.IsPointerType() && rightType.IsStringType())))
{
Assert.False(leftType.IsStringType() && rightType.IsStringType());
if (leftType.IsStringType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, leftType, compilation.ObjectType, leftType);
}
else
{
Assert.True(rightType.IsStringType());
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, compilation.ObjectType, rightType, rightType);
}
}
else if (op == BinaryOperatorKind.Addition &&
(((leftType.IsIntegralType() || leftType.IsCharType()) && rightType.IsPointerType()) ||
(leftType.IsPointerType() && (rightType.IsIntegralType() || rightType.IsCharType()))))
{
if (leftType.IsPointerType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, leftType, symbol1.Parameters[1].Type.GetSymbol(), leftType);
Assert.True(symbol1.Parameters[1].Type.GetSymbol().IsIntegralType());
}
else
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, symbol1.Parameters[0].Type.GetSymbol(), rightType, rightType);
Assert.True(symbol1.Parameters[0].Type.GetSymbol().IsIntegralType());
}
}
else if (op == BinaryOperatorKind.Subtraction &&
(leftType.IsPointerType() && (rightType.IsIntegralType() || rightType.IsCharType())))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, leftType, symbol1.Parameters[1].Type.GetSymbol(), leftType);
Assert.True(symbol1.Parameters[1].Type.GetSymbol().IsIntegralType());
}
else if (op == BinaryOperatorKind.Subtraction && leftType.IsPointerType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, leftType, rightType, compilation.GetSpecialType(SpecialType.System_Int64));
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
leftType.IsEnumType() && (rightType.IsIntegralType() || rightType.IsCharType()) &&
(result = OverloadResolution.BinopEasyOut.OpKind(op, leftType.EnumUnderlyingTypeOrSelf(), rightType)) != BinaryOperatorKind.Error &&
TypeSymbol.Equals((signature = compilation.builtInOperators.GetSignature(result)).RightType, leftType.EnumUnderlyingTypeOrSelf(), TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(signature.Kind | BinaryOperatorKind.EnumAndUnderlying, leftType, signature.RightType, leftType);
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
rightType.IsEnumType() && (leftType.IsIntegralType() || leftType.IsCharType()) &&
(result = OverloadResolution.BinopEasyOut.OpKind(op, leftType, rightType.EnumUnderlyingTypeOrSelf())) != BinaryOperatorKind.Error &&
TypeSymbol.Equals((signature = compilation.builtInOperators.GetSignature(result)).LeftType, rightType.EnumUnderlyingTypeOrSelf(), TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(signature.Kind | BinaryOperatorKind.EnumAndUnderlying, signature.LeftType, rightType, rightType);
}
else if (op == BinaryOperatorKind.Subtraction &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, leftType.EnumUnderlyingTypeOrSelf());
}
else if ((op == BinaryOperatorKind.Equal ||
op == BinaryOperatorKind.NotEqual ||
op == BinaryOperatorKind.LessThan ||
op == BinaryOperatorKind.LessThanOrEqual ||
op == BinaryOperatorKind.GreaterThan ||
op == BinaryOperatorKind.GreaterThanOrEqual) &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, compilation.GetSpecialType(SpecialType.System_Boolean));
}
else if ((op == BinaryOperatorKind.Xor ||
op == BinaryOperatorKind.And ||
op == BinaryOperatorKind.Or) &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, leftType);
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
leftType.IsDelegateType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate, leftType, leftType, leftType);
}
else if ((op == BinaryOperatorKind.Equal ||
op == BinaryOperatorKind.NotEqual ||
op == BinaryOperatorKind.LessThan ||
op == BinaryOperatorKind.LessThanOrEqual ||
op == BinaryOperatorKind.GreaterThan ||
op == BinaryOperatorKind.GreaterThanOrEqual) &&
leftType.IsPointerType() && rightType.IsPointerType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer,
compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Void)),
compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Void)),
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else
{
if ((object)symbol1 != null)
{
Assert.False(symbol1.IsImplicitlyDeclared);
Assert.Equal(MethodKind.UserDefinedOperator, symbol1.MethodKind);
if (leftType.IsValueType && !leftType.IsPointerType())
{
if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Same(symbol1, symbol2);
Assert.Same(symbol1, symbol3);
Assert.Same(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
Assert.Same(symbol1, symbol3);
Assert.Null(symbol4);
return;
}
}
else if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Same(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
}
Assert.Null(symbol1);
Assert.Null(symbol2);
if (!rightType.IsDynamic())
{
Assert.Null(symbol3);
}
if (!leftType.IsDynamic())
{
Assert.Null(symbol4);
}
return;
}
}
else if ((op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) &&
!TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2) &&
(!leftType.IsValueType || !rightType.IsValueType ||
leftType.SpecialType == SpecialType.System_Boolean || rightType.SpecialType == SpecialType.System_Boolean ||
(leftType.SpecialType == SpecialType.System_Decimal && (rightType.SpecialType == SpecialType.System_Double || rightType.SpecialType == SpecialType.System_Single)) ||
(rightType.SpecialType == SpecialType.System_Decimal && (leftType.SpecialType == SpecialType.System_Double || leftType.SpecialType == SpecialType.System_Single))) &&
(!leftType.IsReferenceType || !rightType.IsReferenceType ||
!compilation.Conversions.ClassifyConversionFromType(leftType, rightType, ref useSiteDiagnostics).IsReference))
{
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
else
{
signature = compilation.builtInOperators.GetSignature(result);
}
Assert.NotNull(symbol1);
string containerName = signature.LeftType.ToTestDisplayString();
string leftName = containerName;
string rightName = signature.RightType.ToTestDisplayString();
string returnName = signature.ReturnType.ToTestDisplayString();
if (isDynamic)
{
containerName = compilation.DynamicType.ToTestDisplayString();
}
else if (op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction)
{
if (signature.LeftType.IsObjectType() && signature.RightType.IsStringType())
{
containerName = rightName;
}
else if ((leftType.IsEnumType() || leftType.IsPointerType()) && (rightType.IsIntegralType() || rightType.IsCharType()))
{
containerName = leftType.ToTestDisplayString();
leftName = containerName;
returnName = containerName;
}
else if ((rightType.IsEnumType() || rightType.IsPointerType()) && (leftType.IsIntegralType() || leftType.IsCharType()))
{
containerName = rightType.ToTestDisplayString();
rightName = containerName;
returnName = containerName;
}
}
Assert.Equal(isDynamic, signature.ReturnType.IsDynamic());
string expectedSymbol = String.Format("{4} {0}.{2}({1} left, {3} right)",
containerName,
leftName,
OperatorFacts.BinaryOperatorNameFromOperatorKind(op),
rightName,
returnName);
string actualSymbol = symbol1.ToTestDisplayString();
Assert.Equal(expectedSymbol, actualSymbol);
Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind);
Assert.True(symbol1.IsImplicitlyDeclared);
bool isChecked;
switch (op)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Division:
isChecked = isDynamic || symbol1.ContainingSymbol.Kind == SymbolKind.PointerType || symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType();
break;
default:
isChecked = isDynamic;
break;
}
Assert.Equal(isChecked, symbol1.IsCheckedBuiltin);
Assert.False(symbol1.IsGenericMethod);
Assert.False(symbol1.IsExtensionMethod);
Assert.False(symbol1.IsExtern);
Assert.False(symbol1.CanBeReferencedByName);
Assert.Null(symbol1.GetSymbol().DeclaringCompilation);
Assert.Equal(symbol1.Name, symbol1.MetadataName);
Assert.True(SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[0].Type) ||
SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[1].Type));
int match = 0;
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.ReturnType))
{
match++;
}
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[0].Type))
{
match++;
}
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[1].Type))
{
match++;
}
Assert.True(match >= 2);
Assert.Equal(0, symbol1.Locations.Length);
Assert.Null(symbol1.GetDocumentationCommentId());
Assert.Equal("", symbol1.GetDocumentationCommentXml());
Assert.True(symbol1.GetSymbol().HasSpecialName);
Assert.True(symbol1.IsStatic);
Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility);
Assert.False(symbol1.HidesBaseMethodsByName);
Assert.False(symbol1.IsOverride);
Assert.False(symbol1.IsVirtual);
Assert.False(symbol1.IsAbstract);
Assert.False(symbol1.IsSealed);
Assert.Equal(2, symbol1.Parameters.Length);
Assert.Equal(0, symbol1.Parameters[0].Ordinal);
Assert.Equal(1, symbol1.Parameters[1].Ordinal);
var otherSymbol = (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol;
Assert.Equal(symbol1, otherSymbol);
if (leftType.IsValueType && !leftType.IsPointerType())
{
if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Equal(symbol1, symbol2);
Assert.Equal(symbol1, symbol3);
Assert.Equal(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
if (rightType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol3);
}
else
{
Assert.Equal(rightType.IsPointerType() ? null : symbol1, symbol3);
}
Assert.Null(symbol4);
return;
}
}
else if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Null(symbol2);
Assert.Null(symbol3);
if (leftType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol4);
}
else
{
Assert.Equal(leftType.IsPointerType() ? null : symbol1, symbol4);
}
return;
}
Assert.Null(symbol2);
if (rightType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol3);
}
else
{
Assert.Null(symbol3);
}
if (leftType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol4);
}
else
{
Assert.Null(symbol4);
}
}
[Fact()]
public void BinaryIntrinsicSymbols3()
{
var source =
@"
class Module1
{
void Test(object x)
{
var z1 = x as string;
var z2 = x is string;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
foreach (var node1 in nodes)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
Assert.Null(info1.Symbol);
Assert.Equal(0, info1.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, info1.CandidateReason);
}
}
[Fact()]
public void CheckedBinaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(int x, int y)
{
var z1 = x + y;
x += y;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = tree.GetRoot().DescendantNodes().Where(node => node is BinaryExpressionSyntax || node is AssignmentExpressionSyntax).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[Fact()]
public void DynamicBinaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(dynamic x)
{
var z1 = x == null;
var z2 = null == x;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
Assert.True(((ITypeSymbol)symbol1.ContainingSymbol).IsDynamic());
Assert.Null(symbol1.ContainingType);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
Assert.True(((ITypeSymbol)symbol2.ContainingSymbol).IsDynamic());
Assert.Null(symbol2.ContainingType);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[Fact(), WorkItem(721565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/721565")]
public void Bug721565()
{
var source =
@"
class Module1
{
void Test(TestStr? x, int? y, TestStr? x1, int? y1)
{
var z1 = (x == null);
var z2 = (x != null);
var z3 = (null == x);
var z4 = (null != x);
var z5 = (y == null);
var z6 = (y != null);
var z7 = (null == y);
var z8 = (null != y);
var z9 = (y == y1);
var z10 = (y != y1);
var z11 = (x == x1);
var z12 = (x != x1);
}
}
struct TestStr
{}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (17,20): error CS0019: Operator '==' cannot be applied to operands of type 'TestStr?' and 'TestStr?'
// var z11 = (x == x1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == x1").WithArguments("==", "TestStr?", "TestStr?"),
// (18,20): error CS0019: Operator '!=' cannot be applied to operands of type 'TestStr?' and 'TestStr?'
// var z12 = (x != x1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x != x1").WithArguments("!=", "TestStr?", "TestStr?")
);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(12, nodes.Length);
for (int i = 0; i < 12; i++)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(nodes[i]);
switch (i)
{
case 0:
case 2:
case 4:
case 6:
Assert.Equal("System.Boolean System.Object.op_Equality(System.Object left, System.Object right)", info1.Symbol.ToTestDisplayString());
break;
case 1:
case 3:
case 5:
case 7:
Assert.Equal("System.Boolean System.Object.op_Inequality(System.Object left, System.Object right)", info1.Symbol.ToTestDisplayString());
break;
case 8:
Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", info1.Symbol.ToTestDisplayString());
break;
case 9:
Assert.Equal("System.Boolean System.Int32.op_Inequality(System.Int32 left, System.Int32 right)", info1.Symbol.ToTestDisplayString());
break;
case 10:
case 11:
Assert.Null(info1.Symbol);
break;
default:
throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(i);
}
}
}
[Fact]
public void IntrinsicBinaryOperatorSignature_EqualsAndGetHashCode()
{
var source =
@"class C
{
static object F(int i)
{
return i += 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
var methodBody = methodDecl.Body;
var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(methodBody.SpanStart);
var diagnostics = DiagnosticBag.GetInstance();
var block = binder.BindEmbeddedBlock(methodBody, diagnostics);
diagnostics.Free();
// Rewriter should use Equals.
var rewriter = new EmptyRewriter();
var node = rewriter.Visit(block);
Assert.Same(node, block);
var visitor = new FindCompoundAssignmentWalker();
visitor.Visit(block);
var op = visitor.FirstNode.Operator;
Assert.Null(op.Method);
// Equals and GetHashCode should support null Method.
Assert.Equal(op, new BinaryOperatorSignature(op.Kind, op.LeftType, op.RightType, op.ReturnType, op.Method, constrainedToTypeOpt: null));
op.GetHashCode();
}
[Fact]
public void StrictEnumSubtraction()
{
var source1 =
@"public enum Color { Red, Blue, Green }
public static class Program
{
public static void M<T>(T t) {}
public static void Main(string[] args)
{
M(1 - Color.Red);
}
}";
CreateCompilation(source1, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(
// (7,11): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'Color'
// M(1 - Color.Red);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - Color.Red").WithArguments("-", "int", "Color").WithLocation(7, 11)
);
}
/// <summary>
/// Operators && and || are supported when operators
/// & and | are defined on the same type or a derived type
/// from operators true and false only. This matches Dev12.
/// </summary>
[WorkItem(1079034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079034")]
[Fact]
public void UserDefinedShortCircuitingOperators_TrueAndFalseOnBaseType()
{
var source =
@"class A<T>
{
public static bool operator true(A<T> o) { return true; }
public static bool operator false(A<T> o) { return false; }
}
class B : A<object>
{
public static B operator &(B x, B y) { return x; }
}
class C : B
{
public static C operator |(C x, C y) { return x; }
}
class P
{
static void M(C x, C y)
{
if (x && y)
{
}
if (x || y)
{
}
}
}";
var verifier = CompileAndVerify(source);
verifier.Compilation.VerifyDiagnostics();
verifier.VerifyIL("P.M",
@"
{
// Code size 53 (0x35)
.maxstack 2
.locals init (B V_0,
C V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call ""bool A<object>.op_False(A<object>)""
IL_0008: brtrue.s IL_0013
IL_000a: ldloc.0
IL_000b: ldarg.1
IL_000c: call ""B B.op_BitwiseAnd(B, B)""
IL_0011: br.s IL_0014
IL_0013: ldloc.0
IL_0014: call ""bool A<object>.op_True(A<object>)""
IL_0019: pop
IL_001a: ldarg.0
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: call ""bool A<object>.op_True(A<object>)""
IL_0022: brtrue.s IL_002d
IL_0024: ldloc.1
IL_0025: ldarg.1
IL_0026: call ""C C.op_BitwiseOr(C, C)""
IL_002b: br.s IL_002e
IL_002d: ldloc.1
IL_002e: call ""bool A<object>.op_True(A<object>)""
IL_0033: pop
IL_0034: ret
}");
}
/// <summary>
/// Operators && and || are supported when operators
/// & and | are defined on the same type or a derived type
/// from operators true and false only. This matches Dev12.
/// </summary>
[Fact]
public void UserDefinedShortCircuitingOperators_TrueAndFalseOnDerivedType()
{
var source =
@"class A<T>
{
public static A<T> operator |(A<T> x, A<T> y) { return x; }
}
class B : A<object>
{
public static B operator &(B x, B y) { return x; }
}
class C : B
{
public static bool operator true(C o) { return true; }
public static bool operator false(C o) { return false; }
}
class P
{
static void M(C x, C y)
{
if (x && y)
{
}
if (x || y)
{
}
}
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (18,13): error CS0218: In order for 'B.operator &(B, B)' to be applicable as a short circuit operator, its declaring type 'B' must define operator true and operator false
// if (x && y)
Diagnostic(ErrorCode.ERR_MustHaveOpTF, "x && y").WithArguments("B.operator &(B, B)", "B").WithLocation(18, 13),
// (21,13): error CS0218: In order for 'A<object>.operator |(A<object>, A<object>)' to be applicable as a short circuit operator, its declaring type 'A<object>' must define operator true and operator false
// if (x || y)
Diagnostic(ErrorCode.ERR_MustHaveOpTF, "x || y").WithArguments("A<object>.operator |(A<object>, A<object>)", "A<object>").WithLocation(21, 13));
}
private sealed class EmptyRewriter : BoundTreeRewriter
{
protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node)
{
throw new NotImplementedException();
}
}
private sealed class FindCompoundAssignmentWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
internal BoundCompoundAssignmentOperator FirstNode;
public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
if (FirstNode == null)
{
FirstNode = node;
}
return base.VisitCompoundAssignmentOperator(node);
}
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_0()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
const int y = 0;
x -= y;
}
}
enum E : short { }
";
CompileAndVerify(source: source);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_1()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
x -= new Test();
}
}
enum E : short { }
class Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_2()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
var y = new Test() - x;
}
}
enum E : short { }
class Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_3()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
const int y = 0;
Print(x - y);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}
enum E : short { }";
CompileAndVerify(source: source, expectedOutput: "System.Int16");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_4()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
x -= new Test?(new Test());
}
}
enum E : short { }
struct Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_5()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
var y = new Test?(new Test());
var z = y - x;
}
}
enum E : short { }
struct Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_6()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
const int y = 0;
Print(x - y);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}
enum E : short { }";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Int16]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_7()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
Base64FormattingOptions? xn0 = Base64FormattingOptions.None;
Print(xn0 - 0);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Base64FormattingOptions]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_8()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
Base64FormattingOptions? xn0 = Base64FormattingOptions.None;
Print(0 - xn0);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Int32]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_9()
{
string source = @"
using System;
enum MyEnum1 : short
{
A, B
}
enum MyEnum2
{
A, B
}
class Program
{
static void M<T>(T t)
{
Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
MyEnum1 m1 = (long)0;
M((short)0 - m1);
M((int)0 - m1);
M((long)0 - m1);
MyEnum2 m2 = 0;
M((short)0 - m2);
M((int)0 - m2);
M((long)0 - m2);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Int16
System.Int16
System.Int16
System.Int32
System.Int32
System.Int32");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_10()
{
string source = @"
enum TestEnum : short
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
byte a = 1;
short b = 1;
byte e = 0;
short f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test2()
{
TestEnum? x = 0;
byte a = 1;
short b = 1;
byte e = 0;
short f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test3()
{
TestEnum x = 0;
byte? a = 1;
short? b = 1;
byte? e = 0;
short? f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test4()
{
TestEnum? x = 0;
byte? a = 1;
short? b = 1;
byte? e = 0;
short? f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test5()
{
TestEnum x = 0;
const byte a = 1;
const short b = 1;
const int c = 1;
const byte e = 0;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - a);
Print(x - b);
Print(x - c);
Print(x - e);
Print(x - f);
Print(x - g);
Print(x - h);
Print(a - x);
Print(b - x);
Print(c - x);
Print(e - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const byte a = 1;
const short b = 1;
const int c = 1;
const byte e = 0;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - a);
Print(x - b);
Print(x - c);
Print(x - e);
Print(x - f);
Print(x - g);
Print(x - h);
Print(a - x);
Print(b - x);
Print(c - x);
Print(e - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (byte)1);
Print(x - (short)1);
Print(x - (int)1);
Print(x - (byte)0);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((byte)1 - x);
Print((short)1 - x);
Print((int)1 - x);
Print((byte)0 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (byte)1);
Print(x - (short)1);
Print(x - (int)1);
Print(x - (byte)0);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((byte)1 - x);
Print((short)1 - x);
Print((int)1 - x);
Print((byte)0 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
TestEnum
System.Int16
TestEnum
System.Int16
System.Int16
TestEnum
TestEnum
TestEnum
System.Int16
System.Int16
System.Int16
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
TestEnum
TestEnum
TestEnum
System.Int16
TestEnum
System.Int16
System.Int16
TestEnum
TestEnum
TestEnum
System.Int16
System.Int16
System.Int16
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
TestEnum
System.Int16
TestEnum
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_11()
{
string source = @"
enum TestEnum : short
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
}
static void Test1()
{
TestEnum x = 0;
int c = 1;
long d = 1;
int g = 0;
long h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
int c = 1;
long d = 1;
int g = 0;
long h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
int? c = 1;
long? d = 1;
int? g = 0;
long? h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
int? c = 1;
long? d = 1;
int? g = 0;
long? h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test6()
{
TestEnum? x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (26,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum", "int").WithLocation(26, 15),
// (27,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(27, 15),
// (28,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum", "int").WithLocation(28, 15),
// (29,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long").WithLocation(29, 15),
// (30,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int", "TestEnum").WithLocation(30, 15),
// (31,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(31, 15),
// (32,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int", "TestEnum").WithLocation(32, 15),
// (33,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum").WithLocation(33, 15),
// (44,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum?", "int").WithLocation(44, 15),
// (45,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(45, 15),
// (46,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum?", "int").WithLocation(46, 15),
// (47,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long").WithLocation(47, 15),
// (48,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum?'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int", "TestEnum?").WithLocation(48, 15),
// (49,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(49, 15),
// (50,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum?'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int", "TestEnum?").WithLocation(50, 15),
// (51,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum?").WithLocation(51, 15),
// (62,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int?'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum", "int?").WithLocation(62, 15),
// (63,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long?").WithLocation(63, 15),
// (64,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int?'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum", "int?").WithLocation(64, 15),
// (65,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long?").WithLocation(65, 15),
// (66,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int?", "TestEnum").WithLocation(66, 15),
// (67,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum").WithLocation(67, 15),
// (68,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int?", "TestEnum").WithLocation(68, 15),
// (69,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum").WithLocation(69, 15),
// (80,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int?'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum?", "int?").WithLocation(80, 15),
// (81,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long?").WithLocation(81, 15),
// (82,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int?'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum?", "int?").WithLocation(82, 15),
// (83,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long?").WithLocation(83, 15),
// (84,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum?'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int?", "TestEnum?").WithLocation(84, 15),
// (85,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum?").WithLocation(85, 15),
// (86,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum?'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int?", "TestEnum?").WithLocation(86, 15),
// (87,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum?").WithLocation(87, 15),
// (95,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(95, 15),
// (96,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(96, 15),
// (104,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(104, 15),
// (105,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(105, 15),
// (112,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum", "long").WithLocation(112, 15),
// (113,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum").WithLocation(113, 15),
// (120,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum?", "long").WithLocation(120, 15),
// (121,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum?").WithLocation(121, 15)
);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_12()
{
string source = @"
enum TestEnum : int
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
short b = 1;
int c = 1;
short f = 0;
int g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test2()
{
TestEnum? x = 0;
short b = 1;
int c = 1;
short f = 0;
int g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test3()
{
TestEnum x = 0;
short? b = 1;
int? c = 1;
short? f = 0;
int? g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test4()
{
TestEnum? x = 0;
short? b = 1;
int? c = 1;
short? f = 0;
int? g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test5()
{
TestEnum x = 0;
const short b = 1;
const int c = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const short b = 1;
const int c = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
System.Int32
TestEnum
System.Int32
TestEnum
TestEnum
System.Int32
System.Int32
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
TestEnum
TestEnum
System.Int32
TestEnum
System.Int32
TestEnum
TestEnum
System.Int32
System.Int32
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
TestEnum
TestEnum
TestEnum
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_13()
{
string source = @"
enum TestEnum : int
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
}
static void Test1()
{
TestEnum x = 0;
long d = 1;
long h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
long d = 1;
long h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
long? d = 1;
long? h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
long? d = 1;
long? h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test6()
{
TestEnum? x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (24,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(24, 15),
// (25,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long").WithLocation(25, 15),
// (26,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(26, 15),
// (27,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum").WithLocation(27, 15),
// (36,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(36, 15),
// (37,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long").WithLocation(37, 15),
// (38,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(38, 15),
// (39,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum?").WithLocation(39, 15),
// (48,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long?").WithLocation(48, 15),
// (49,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long?").WithLocation(49, 15),
// (50,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum").WithLocation(50, 15),
// (51,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum").WithLocation(51, 15),
// (60,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long?").WithLocation(60, 15),
// (61,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long?").WithLocation(61, 15),
// (62,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum?").WithLocation(62, 15),
// (63,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum?").WithLocation(63, 15),
// (71,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(71, 15),
// (72,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(72, 15),
// (80,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(80, 15),
// (81,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(81, 15),
// (88,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum", "long").WithLocation(88, 15),
// (89,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum").WithLocation(89, 15),
// (96,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum?", "long").WithLocation(96, 15),
// (97,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum?").WithLocation(97, 15)
);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_14()
{
string source = @"
enum TestEnum : long
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
short b = 1;
int c = 1;
long d = 1;
short f = 0;
int g = 0;
long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
short b = 1;
int c = 1;
long d = 1;
short f = 0;
int g = 0;
long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
short? b = 1;
int? c = 1;
long? d = 1;
short? f = 0;
int? g = 0;
long? h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
short? b = 1;
int? c = 1;
long? d = 1;
short? f = 0;
int? g = 0;
long? h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const short b = 1;
const int c = 1;
const long d = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const short b = 1;
const int c = 1;
const long d = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (long)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((long)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (long)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((long)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
TestEnum
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
TestEnum
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
TestEnum
System.Int64
TestEnum
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_15()
{
string source = @"
enum TestEnumShort : short
{}
enum TestEnumInt : int
{ }
enum TestEnumLong : long
{ }
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
}
static void Test1()
{
TestEnumShort? x = 0;
Print(x - null);
Print(null - x);
}
static void Test2()
{
TestEnumInt? x = 0;
Print(x - null);
Print(null - x);
}
static void Test3()
{
TestEnumLong? x = 0;
Print(x - null);
Print(null - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_16()
{
string source = @"
enum TestEnumShort : short
{}
enum TestEnumInt : int
{ }
enum TestEnumLong : long
{ }
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
}
static void Test1()
{
TestEnumShort x = 0;
Print(x - null);
Print(null - x);
}
static void Test2()
{
TestEnumInt x = 0;
Print(x - null);
Print(null - x);
}
static void Test3()
{
TestEnumLong x = 0;
Print(x - null);
Print(null - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_01()
{
string source = @"
class Test
{
static void Main()
{
Test0();
Test1();
Test2();
Test3();
Test4();
}
static void Test0()
{
Print(((System.TypeCode)0) as int?);
Print(0 as int?);
Print(((int?)0) as int?);
Print(0 as long?);
Print(0 as ulong?);
Print(GetNullableInt() as long?);
}
static int? GetNullableInt()
{
return 0;
}
static void Test1()
{
var c1 = new C1<int>();
c1.M1(0);
}
static void Test2()
{
var c1 = new C1<ulong>();
c1.M1<ulong>(0);
}
static void Test3()
{
var c1 = new C2();
c1.M1(0);
}
static void Test4()
{
var c1 = new C3();
c1.M1<int?>(0);
}
public static void Print<T>(T? v) where T : struct
{
System.Console.WriteLine(v.HasValue);
}
}
class C1<T>
{
public virtual void M1<S>(S x) where S :T
{
Test.Print(x as ulong?);
}
}
class C2 : C1<int>
{
public override void M1<S>(S x)
{
Test.Print(x as ulong?);
}
}
class C3 : C1<int?>
{
public override void M1<S>(S x)
{
Test.Print(x as ulong?);
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput:
@"False
True
True
False
False
False
False
True
False
False
");
verifier.VerifyIL("Test.Test0",
@"
{
// Code size 85 (0x55)
.maxstack 1
.locals init (int? V_0,
long? V_1,
ulong? V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""int?""
IL_0008: ldloc.0
IL_0009: call ""void Test.Print<int>(int?)""
IL_000e: ldc.i4.0
IL_000f: newobj ""int?..ctor(int)""
IL_0014: call ""void Test.Print<int>(int?)""
IL_0019: ldc.i4.0
IL_001a: newobj ""int?..ctor(int)""
IL_001f: call ""void Test.Print<int>(int?)""
IL_0024: ldloca.s V_1
IL_0026: initobj ""long?""
IL_002c: ldloc.1
IL_002d: call ""void Test.Print<long>(long?)""
IL_0032: ldloca.s V_2
IL_0034: initobj ""ulong?""
IL_003a: ldloc.2
IL_003b: call ""void Test.Print<ulong>(ulong?)""
IL_0040: call ""int? Test.GetNullableInt()""
IL_0045: pop
IL_0046: ldloca.s V_1
IL_0048: initobj ""long?""
IL_004e: ldloc.1
IL_004f: call ""void Test.Print<long>(long?)""
IL_0054: ret
}");
verifier.VerifyIL("C1<T>.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyIL("C2.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyIL("C3.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyDiagnostics(
// (15,15): warning CS0458: The result of the expression is always 'null' of type 'int?'
// Print(((System.TypeCode)0) as int?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "((System.TypeCode)0) as int?").WithArguments("int?").WithLocation(15, 15),
// (18,15): warning CS0458: The result of the expression is always 'null' of type 'long?'
// Print(0 as long?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "0 as long?").WithArguments("long?").WithLocation(18, 15),
// (19,15): warning CS0458: The result of the expression is always 'null' of type 'ulong?'
// Print(0 as ulong?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "0 as ulong?").WithArguments("ulong?").WithLocation(19, 15),
// (20,15): warning CS0458: The result of the expression is always 'null' of type 'long?'
// Print(GetNullableInt() as long?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "GetNullableInt() as long?").WithArguments("long?").WithLocation(20, 15)
);
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_02()
{
string source = @"
using System;
class Program
{
static void Main()
{
var x = 0 as long?;
Console.WriteLine(x.HasValue);
var y = 0 as ulong?;
Console.WriteLine(y.HasValue);
}
}
";
CompileAndVerify(source: source, expectedOutput:
@"False
False
");
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_03()
{
string source = @"
class Test
{
static void Main()
{
Test0();
}
static void Test0()
{
var c2 = new C2();
c2.M1<C1>(null);
}
public static void Print<T>(T v) where T : class
{
System.Console.WriteLine(v != null);
}
}
class C1
{}
class C2
{
public void M1<S>(C1 x) where S : C1
{
Test.Print(x as S);
Test.Print(((C1)null) as S);
}
}";
var verifier = CompileAndVerify(source: source, expectedOutput:
@"False
False
");
verifier.VerifyIL("C2.M1<S>",
@"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (S V_0)
IL_0000: ldarg.1
IL_0001: isinst ""S""
IL_0006: unbox.any ""S""
IL_000b: call ""void Test.Print<S>(S)""
IL_0010: ldloca.s V_0
IL_0012: initobj ""S""
IL_0018: ldloc.0
IL_0019: call ""void Test.Print<S>(S)""
IL_001e: ret
}");
}
[Fact, WorkItem(2075, "https://github.com/dotnet/roslyn/issues/2075")]
public void NegateALiteral()
{
string source = @"
using System;
namespace roslynChanges
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ((-(2147483648)).GetType ());
Console.WriteLine ((-2147483648).GetType ());
}
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Int64
System.Int32
");
}
[Fact, WorkItem(4132, "https://github.com/dotnet/roslyn/issues/4132")]
public void Issue4132()
{
string source = @"
using System;
namespace NullableMathRepro
{
class Program
{
static void Main(string[] args)
{
int? x = 0;
x += 5;
Console.WriteLine(""'x' is {0}"", x);
IntHolder? y = 0;
y += 5;
Console.WriteLine(""'y' is {0}"", y);
}
}
struct IntHolder
{
private int x;
public static implicit operator int (IntHolder ih)
{
Console.WriteLine(""operator int (IntHolder ih)"");
return ih.x;
}
public static implicit operator IntHolder(int i)
{
Console.WriteLine(""operator IntHolder(int i)"");
return new IntHolder { x = i };
}
public override string ToString()
{
return x.ToString();
}
}
}";
CompileAndVerify(source: source, expectedOutput:
@"'x' is 5
operator IntHolder(int i)
operator int (IntHolder ih)
operator IntHolder(int i)
'y' is 5");
}
[Fact, WorkItem(8190, "https://github.com/dotnet/roslyn/issues/8190")]
public void Issue8190_1()
{
string source = @"
using System;
namespace RoslynNullableStringRepro
{
public class Program
{
public static void Main(string[] args)
{
NonNullableString? irony = ""abc"";
irony += ""def"";
string ynori = ""abc"";
ynori += (NonNullableString?)""def"";
Console.WriteLine(irony);
Console.WriteLine(ynori);
ynori += (NonNullableString?) null;
Console.WriteLine(ynori);
}
}
struct NonNullableString
{
NonNullableString(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
this.value = value;
}
readonly string value;
public override string ToString() => value;
public static implicit operator string(NonNullableString self) => self.value;
public static implicit operator NonNullableString(string value) => new NonNullableString(value);
public static string operator +(NonNullableString lhs, NonNullableString rhs) => lhs.value + rhs.value;
}
}";
CompileAndVerify(source: source, expectedOutput: "abcdef" + Environment.NewLine + "abcdef" + Environment.NewLine + "abcdef");
}
[Fact, WorkItem(8190, "https://github.com/dotnet/roslyn/issues/8190")]
public void Issue8190_2()
{
string source = @"
using System;
namespace RoslynNullableIntRepro
{
public class Program
{
public static void Main(string[] args)
{
NonNullableInt? irony = 1;
irony += 2;
int? ynori = 1;
ynori += (NonNullableInt?) 2;
Console.WriteLine(irony);
Console.WriteLine(ynori);
ynori += (NonNullableInt?) null;
Console.WriteLine(ynori);
}
}
struct NonNullableInt
{
NonNullableInt(int? value)
{
if (value == null)
{
throw new ArgumentNullException();
}
this.value = value;
}
readonly int? value;
public override string ToString() {return value.ToString();}
public static implicit operator int? (NonNullableInt self) {return self.value;}
public static implicit operator NonNullableInt(int? value) {return new NonNullableInt(value);}
public static int? operator +(NonNullableInt lhs, NonNullableInt rhs) { return lhs.value + rhs.value; }
}
}";
CompileAndVerify(source: source, expectedOutput: "3" + Environment.NewLine + "3" + Environment.NewLine);
}
[Fact, WorkItem(4027, "https://github.com/dotnet/roslyn/issues/4027")]
public void NotSignExtendedOperand()
{
string source = @"
class MainClass
{
public static void Main ()
{
short a = 0;
int b = 0;
a |= (short)b;
a = (short)(a | (short)b);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
}
[Fact]
[WorkItem(12345, "https://github.com/dotnet/roslyn/issues/12345")]
public void Bug12345()
{
string source = @"
class EnumRepro
{
public static void Main()
{
EnumWrapper<FlagsEnum> wrappedEnum = FlagsEnum.Goo;
wrappedEnum |= FlagsEnum.Bar;
System.Console.Write(wrappedEnum.Enum);
}
}
public struct EnumWrapper<T>
where T : struct
{
public T? Enum { get; private set; }
public static implicit operator T? (EnumWrapper<T> safeEnum)
{
return safeEnum.Enum;
}
public static implicit operator EnumWrapper<T>(T source)
{
return new EnumWrapper<T> { Enum = source };
}
}
[System.Flags]
public enum FlagsEnum
{
None = 0,
Goo = 1,
Bar = 2,
}
";
var verifier = CompileAndVerify(source, expectedOutput: "Goo, Bar");
verifier.VerifyDiagnostics();
}
[Fact]
public void IsWarningWithNonNullConstant()
{
var source =
@"class Program
{
public static void Main(string[] args)
{
const string d = ""goo"";
var x = d is string;
}
}
";
var compilation = CreateCompilation(source)
.VerifyDiagnostics(
// (6,17): warning CS0183: The given expression is always of the provided ('string') type
// var x = d is string;
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "d is string").WithArguments("string").WithLocation(6, 17)
);
}
[Fact, WorkItem(19310, "https://github.com/dotnet/roslyn/issues/19310")]
public void IsWarningWithTupleConversion()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var t = (x: 1, y: 2);
if (t is ValueTuple<long, int>) { } // too big
if (t is ValueTuple<short, int>) { } // too small
if (t is ValueTuple<int, int>) { } // goldilocks
}
}";
var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef })
.VerifyDiagnostics(
// (7,13): warning CS0184: The given expression is never of the provided ('(long, int)') type
// if (t is ValueTuple<long, int>) { } // too big
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is ValueTuple<long, int>").WithArguments("(long, int)").WithLocation(7, 13),
// (8,13): warning CS0184: The given expression is never of the provided ('(short, int)') type
// if (t is ValueTuple<short, int>) { } // too small
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is ValueTuple<short, int>").WithArguments("(short, int)").WithLocation(8, 13),
// (9,13): warning CS0183: The given expression is always of the provided ('(int, int)') type
// if (t is ValueTuple<int, int>) { } // goldilocks
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "t is ValueTuple<int, int>").WithArguments("(int, int)").WithLocation(9, 13)
);
}
[Fact, WorkItem(21486, "https://github.com/dotnet/roslyn/issues/21486")]
public void TypeOfErrorUnaryOperator()
{
var source =
@"
public class C {
public void M2() {
var local = !invalidExpression;
if (local) { }
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,22): error CS0103: The name 'invalidExpression' does not exist in the current context
// var local = !invalidExpression;
Diagnostic(ErrorCode.ERR_NameNotInContext, "invalidExpression").WithArguments("invalidExpression").WithLocation(4, 22)
);
var tree = compilation.SyntaxTrees.Single();
var negNode = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("!invalidExpression", negNode.ToString());
var type = (ITypeSymbol)compilation.GetSemanticModel(tree).GetTypeInfo(negNode).Type;
Assert.Equal("?", type.ToTestDisplayString());
Assert.True(type.IsErrorType());
}
// Attempting to call `ConstantValue` on every constituent string component realizes every string, effectively
// replicating the original O(n^2) bug that this test is demonstrating is fixed.
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(43019, "https://github.com/dotnet/roslyn/issues/43019"), WorkItem(529600, "DevDiv"), WorkItem(7398, "https://github.com/dotnet/roslyn/issues/7398")]
public void Bug529600()
{
// History of this bug: When constant folding a long sequence of string concatentations, there is
// an intermediate constant value for every left-hand operand. So the total memory consumed to
// compute the whole concatenation was O(n^2). The compiler would simply perform this work and
// eventually run out of memory, simply crashing with no useful diagnostic. Later, the concatenation
// implementation was instrumented so it would detect when it was likely to run out of memory soon,
// and would instead report a diagnostic at the last step. This test was added to demonstrate that
// we produced a diagnostic. However, the compiler still consumed O(n^2) memory for the
// concatenation and this test used to consume so much memory that it would cause other tests running
// in parallel to fail because they might not have enough memory to succeed. So the test was
// disabled and eventually removed. The compiler would still crash with programs containing large
// string concatenations, so the underlying problem had not been addressed. Now we have revised the
// implementation of constant folding so that it requires O(n) memory. As a consequence this test now
// runs very quickly and does not consume gobs of memory.
string source = $@"
class M
{{
static void Main()
{{}}
const string C0 = ""{new string('0', 65000)}"";
const string C1 = C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0;
const string C2 = C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1;
}}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (28,68): error CS8095: Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.
// C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
Diagnostic(ErrorCode.ERR_ConstantStringTooLong, "C1").WithLocation(28, 68)
);
// If we realize every string constant value when each IOperation is created, then attempting to enumerate all
// IOperations will consume O(n^2) memory. This demonstrates that these values are not eagerly created, and the
// test runs quickly and without issue
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var fieldInitializerOperations = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>()
.Select(v => v.Initializer.Value)
.Select(i => model.GetOperation(i));
int numChildren = 0;
foreach (var initializerOp in fieldInitializerOperations)
{
enumerateChildren(initializerOp);
}
Assert.Equal(1203, numChildren);
void enumerateChildren(IOperation iop)
{
numChildren++;
Assert.NotNull(iop);
foreach (var child in iop.Children)
{
enumerateChildren(child);
}
}
}
[Fact, WorkItem(39975, "https://github.com/dotnet/roslyn/issues/39975")]
public void EnsureOperandsConvertedInErrorExpression_01()
{
string source =
@"class C
{
static unsafe void M(dynamic d, int* p)
{
d += p;
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (5,9): error CS0019: Operator '+=' cannot be applied to operands of type 'dynamic' and 'int*'
// d += p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d += p").WithArguments("+=", "dynamic", "int*").WithLocation(5, 9)
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Xunit;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class SyntaxBinderTests : CompilingTestBase
{
[Fact, WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
public void EnumBinaryOps()
{
string source = @"
[Flags]
internal enum TestEnum
{
None,
Tags,
FilePath,
Capabilities,
Visibility,
AllProperties = FilePath | Visibility
}
class C {
public void Goo(){
var x = TestEnum.FilePath | TestEnum.Visibility;
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var orNodes = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().ToArray();
Assert.Equal(2, orNodes.Length);
var insideEnumDefinition = semanticModel.GetSymbolInfo(orNodes[0]);
var insideMethodBody = semanticModel.GetSymbolInfo(orNodes[1]);
Assert.False(insideEnumDefinition.IsEmpty);
Assert.False(insideMethodBody.IsEmpty);
Assert.NotEqual(insideEnumDefinition, insideMethodBody);
Assert.Equal("System.Int32 System.Int32.op_BitwiseOr(System.Int32 left, System.Int32 right)", insideEnumDefinition.Symbol.ToTestDisplayString());
Assert.Equal("TestEnum TestEnum.op_BitwiseOr(TestEnum left, TestEnum right)", insideMethodBody.Symbol.ToTestDisplayString());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void EnumBinaryOps_IOperation()
{
string source = @"
using System;
[Flags]
internal enum TestEnum
{
None,
Tags,
FilePath,
Capabilities,
Visibility,
AllProperties = FilePath | Visibility
}
class C
{
public void Goo()
{
var x = /*<bind>*/TestEnum.FilePath | TestEnum.Visibility/*</bind>*/;
Console.Write(x);
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: TestEnum, Constant: 6) (Syntax: 'TestEnum.Fi ... .Visibility')
Left:
IFieldReferenceOperation: TestEnum.FilePath (Static) (OperationKind.FieldReference, Type: TestEnum, Constant: 2) (Syntax: 'TestEnum.FilePath')
Instance Receiver:
null
Right:
IFieldReferenceOperation: TestEnum.Visibility (Static) (OperationKind.FieldReference, Type: TestEnum, Constant: 4) (Syntax: 'TestEnum.Visibility')
Instance Receiver:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(543895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543895")]
public void TestBug11947()
{
// Due to a long-standing bug, the native compiler allows underlying-enum with the same
// semantics as enum-underlying. (That is, the math is done in the underlying type and
// then cast back to the enum type.)
string source = @"
using System;
public enum E { Zero, One, Two };
class Test
{
static void Main()
{
E e = E.One;
int x = 3;
E r = x - e;
Console.Write(r);
E? en = E.Two;
int? xn = 2;
E? rn = xn - en;
Console.Write(rn);
}
}";
CompileAndVerify(source: source, expectedOutput: "TwoZero");
}
private const string StructWithUserDefinedBooleanOperators = @"
struct S
{
private int num;
private string str;
public S(int num, char chr)
{
this.num = num;
this.str = chr.ToString();
}
public S(int num, string str)
{
this.num = num;
this.str = str;
}
public static S operator & (S x, S y)
{
return new S(x.num & y.num, '(' + x.str + '&' + y.str + ')');
}
public static S operator | (S x, S y)
{
return new S(x.num | y.num, '(' + x.str + '|' + y.str + ')');
}
public static bool operator true(S s)
{
return s.num != 0;
}
public static bool operator false(S s)
{
return s.num == 0;
}
public override string ToString()
{
return this.num.ToString() + ':' + this.str;
}
}
";
[Fact]
public void TestUserDefinedLogicalOperators()
{
string source = @"
using System;
class C
{
static void Main()
{
S f = new S(0, 'f');
S t = new S(1, 't');
Console.WriteLine((f && f) && f);
Console.WriteLine((f && f) && t);
Console.WriteLine((f && t) && f);
Console.WriteLine((f && t) && t);
Console.WriteLine((t && f) && f);
Console.WriteLine((t && f) && t);
Console.WriteLine((t && t) && f);
Console.WriteLine((t && t) && t);
Console.WriteLine('-');
Console.WriteLine((f && f) || f);
Console.WriteLine((f && f) || t);
Console.WriteLine((f && t) || f);
Console.WriteLine((f && t) || t);
Console.WriteLine((t && f) || f);
Console.WriteLine((t && f) || t);
Console.WriteLine((t && t) || f);
Console.WriteLine((t && t) || t);
Console.WriteLine('-');
Console.WriteLine((f || f) && f);
Console.WriteLine((f || f) && t);
Console.WriteLine((f || t) && f);
Console.WriteLine((f || t) && t);
Console.WriteLine((t || f) && f);
Console.WriteLine((t || f) && t);
Console.WriteLine((t || t) && f);
Console.WriteLine((t || t) && t);
Console.WriteLine('-');
Console.WriteLine((f || f) || f);
Console.WriteLine((f || f) || t);
Console.WriteLine((f || t) || f);
Console.WriteLine((f || t) || t);
Console.WriteLine((t || f) || f);
Console.WriteLine((t || f) || t);
Console.WriteLine((t || t) || f);
Console.WriteLine((t || t) || t);
Console.WriteLine('-');
Console.WriteLine(f && (f && f));
Console.WriteLine(f && (f && t));
Console.WriteLine(f && (t && f));
Console.WriteLine(f && (t && t));
Console.WriteLine(t && (f && f));
Console.WriteLine(t && (f && t));
Console.WriteLine(t && (t && f));
Console.WriteLine(t && (t && t));
Console.WriteLine('-');
Console.WriteLine(f && (f || f));
Console.WriteLine(f && (f || t));
Console.WriteLine(f && (t || f));
Console.WriteLine(f && (t || t));
Console.WriteLine(t && (f || f));
Console.WriteLine(t && (f || t));
Console.WriteLine(t && (t || f));
Console.WriteLine(t && (t || t));
Console.WriteLine('-');
Console.WriteLine(f || (f && f));
Console.WriteLine(f || (f && t));
Console.WriteLine(f || (t && f));
Console.WriteLine(f || (t && t));
Console.WriteLine(t || (f && f));
Console.WriteLine(t || (f && t));
Console.WriteLine(t || (t && f));
Console.WriteLine(t || (t && t));
Console.WriteLine('-');
Console.WriteLine(f || (f || f));
Console.WriteLine(f || (f || t));
Console.WriteLine(f || (t || f));
Console.WriteLine(f || (t || t));
Console.WriteLine(t || (f || f));
Console.WriteLine(t || (f || t));
Console.WriteLine(t || (t || f));
Console.WriteLine(t || (t || t));
}
}
" + StructWithUserDefinedBooleanOperators;
string output = @"0:f
0:f
0:f
0:f
0:(t&f)
0:(t&f)
0:((t&t)&f)
1:((t&t)&t)
-
0:(f|f)
1:(f|t)
0:(f|f)
1:(f|t)
0:((t&f)|f)
1:((t&f)|t)
1:(t&t)
1:(t&t)
-
0:(f|f)
0:(f|f)
0:((f|t)&f)
1:((f|t)&t)
0:(t&f)
1:(t&t)
0:(t&f)
1:(t&t)
-
0:((f|f)|f)
1:((f|f)|t)
1:(f|t)
1:(f|t)
1:t
1:t
1:t
1:t
-
0:f
0:f
0:f
0:f
0:(t&f)
0:(t&f)
0:(t&(t&f))
1:(t&(t&t))
-
0:f
0:f
0:f
0:f
0:(t&(f|f))
1:(t&(f|t))
1:(t&t)
1:(t&t)
-
0:(f|f)
0:(f|f)
0:(f|(t&f))
1:(f|(t&t))
1:t
1:t
1:t
1:t
-
0:(f|(f|f))
1:(f|(f|t))
1:(f|t)
1:(f|t)
1:t
1:t
1:t
1:t";
CompileAndVerify(source: source, expectedOutput: output);
}
[Fact]
public void TestUserDefinedLogicalOperators2()
{
string source = @"
using System;
class C
{
static void Main()
{
S f = new S(0, 'f');
S t = new S(1, 't');
Console.Write((f && f) && f ? 1 : 0);
Console.Write((f && f) && t ? 1 : 0);
Console.Write((f && t) && f ? 1 : 0);
Console.Write((f && t) && t ? 1 : 0);
Console.Write((t && f) && f ? 1 : 0);
Console.Write((t && f) && t ? 1 : 0);
Console.Write((t && t) && f ? 1 : 0);
Console.Write((t && t) && t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f && f) || f ? 1 : 0);
Console.Write((f && f) || t ? 1 : 0);
Console.Write((f && t) || f ? 1 : 0);
Console.Write((f && t) || t ? 1 : 0);
Console.Write((t && f) || f ? 1 : 0);
Console.Write((t && f) || t ? 1 : 0);
Console.Write((t && t) || f ? 1 : 0);
Console.Write((t && t) || t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f || f) && f ? 1 : 0);
Console.Write((f || f) && t ? 1 : 0);
Console.Write((f || t) && f ? 1 : 0);
Console.Write((f || t) && t ? 1 : 0);
Console.Write((t || f) && f ? 1 : 0);
Console.Write((t || f) && t ? 1 : 0);
Console.Write((t || t) && f ? 1 : 0);
Console.Write((t || t) && t ? 1 : 0);
Console.WriteLine('-');
Console.Write((f || f) || f ? 1 : 0);
Console.Write((f || f) || t ? 1 : 0);
Console.Write((f || t) || f ? 1 : 0);
Console.Write((f || t) || t ? 1 : 0);
Console.Write((t || f) || f ? 1 : 0);
Console.Write((t || f) || t ? 1 : 0);
Console.Write((t || t) || f ? 1 : 0);
Console.Write((t || t) || t ? 1 : 0);
Console.WriteLine('-');
Console.Write(f && (f && f) ? 1 : 0);
Console.Write(f && (f && t) ? 1 : 0);
Console.Write(f && (t && f) ? 1 : 0);
Console.Write(f && (t && t) ? 1 : 0);
Console.Write(t && (f && f) ? 1 : 0);
Console.Write(t && (f && t) ? 1 : 0);
Console.Write(t && (t && f) ? 1 : 0);
Console.Write(t && (t && t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f && (f || f) ? 1 : 0);
Console.Write(f && (f || t) ? 1 : 0);
Console.Write(f && (t || f) ? 1 : 0);
Console.Write(f && (t || t) ? 1 : 0);
Console.Write(t && (f || f) ? 1 : 0);
Console.Write(t && (f || t) ? 1 : 0);
Console.Write(t && (t || f) ? 1 : 0);
Console.Write(t && (t || t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f || (f && f) ? 1 : 0);
Console.Write(f || (f && t) ? 1 : 0);
Console.Write(f || (t && f) ? 1 : 0);
Console.Write(f || (t && t) ? 1 : 0);
Console.Write(t || (f && f) ? 1 : 0);
Console.Write(t || (f && t) ? 1 : 0);
Console.Write(t || (t && f) ? 1 : 0);
Console.Write(t || (t && t) ? 1 : 0);
Console.WriteLine('-');
Console.Write(f || (f || f) ? 1 : 0);
Console.Write(f || (f || t) ? 1 : 0);
Console.Write(f || (t || f) ? 1 : 0);
Console.Write(f || (t || t) ? 1 : 0);
Console.Write(t || (f || f) ? 1 : 0);
Console.Write(t || (f || t) ? 1 : 0);
Console.Write(t || (t || f) ? 1 : 0);
Console.Write(t || (t || t) ? 1 : 0);
}
}
" + StructWithUserDefinedBooleanOperators;
string output = @"
00000001-
01010111-
00010101-
01111111-
00000001-
00000111-
00011111-
01111111";
CompileAndVerify(source: source, expectedOutput: output);
}
[Fact]
public void TestOperatorTrue()
{
string source = @"
using System;
struct S
{
private int x;
public S(int x) { this.x = x; }
public static bool operator true(S s) { return s.x != 0; }
public static bool operator false(S s) { return s.x == 0; }
}
class C
{
static void Main()
{
S zero = new S(0);
S one = new S(1);
if (zero)
Console.Write('a');
else
Console.Write('b');
if (one)
Console.Write('c');
else
Console.Write('d');
Console.Write( zero ? 'e' : 'f' );
Console.Write( one ? 'g' : 'h' );
while(zero)
{
Console.Write('i');
}
while(one)
{
Console.Write('j');
break;
}
do
{
Console.Write('k');
}
while(zero);
bool first = true;
do
{
Console.Write('l');
if (!first) break;
first = false;
}
while(one);
for( ; zero ; )
{
Console.Write('m');
}
for( ; one ; )
{
Console.Write('n');
break;
}
}
}";
string output = @"bcfgjklln";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestOperatorTrue_IOperation()
{
string source = @"
using System;
struct S
{
private int x;
public S(int x) { this.x = x; }
public static bool operator true(S s) { return s.x != 0; }
public static bool operator false(S s) { return s.x == 0; }
}
class C
{
static void Main(S zero, S one)
/*<bind>*/{
if (zero)
Console.Write('a');
else
Console.Write('b');
Console.Write(one ? 'g' : 'h');
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (zero) ... Write('b');')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S s)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'zero')
Operand:
IParameterReferenceOperation: zero (OperationKind.ParameterReference, Type: S) (Syntax: 'zero')
WhenTrue:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write('a');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write('a')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: ''a'')
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
WhenFalse:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write('b');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write('b')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: ''b'')
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: b) (Syntax: ''b'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... 'g' : 'h');')
Expression:
IInvocationOperation (void System.Console.Write(System.Char value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... 'g' : 'h')')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'one ? 'g' : 'h'')
IConditionalOperation (OperationKind.Conditional, Type: System.Char) (Syntax: 'one ? 'g' : 'h'')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S s)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'one')
Operand:
IParameterReferenceOperation: one (OperationKind.ParameterReference, Type: S) (Syntax: 'one')
WhenTrue:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: g) (Syntax: ''g'')
WhenFalse:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: h) (Syntax: ''h'')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUnaryOperatorOverloading()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator - (S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~ (S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator ! (S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
Console.Write( + ~ ! - a );
Console.Write( a );
Console.Write( a++ );
Console.Write( a );
Console.Write( b );
Console.Write( ++b );
Console.Write( b );
Console.Write( c );
Console.Write( c-- );
Console.Write( c );
Console.Write( d );
Console.Write( --d );
Console.Write( d );
}
}";
string output = "(+(~(!(-a))))aa(a+1)b(b+1)(b+1)cc(c-1)d(d-1)(d-1)";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUnaryOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
Console.Write(+a);
Console.Write(-a);
Console.Write(~a);
Console.Write(!a);
Console.Write(+~!-a);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (5 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(+a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(+a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '+a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '+a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: S S.op_UnaryPlus(S x)) (OperationKind.Unary, Type: S) (Syntax: '+a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(-a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(-a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '-a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '-a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: S S.op_UnaryNegation(S x)) (OperationKind.Unary, Type: S) (Syntax: '-a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(~a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(~a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '~a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '~a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: S S.op_OnesComplement(S x)) (OperationKind.Unary, Type: S) (Syntax: '~a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(!a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(!a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '!a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '!a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: S S.op_LogicalNot(S x)) (OperationKind.Unary, Type: S) (Syntax: '!a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(+~!-a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(+~!-a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '+~!-a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '+~!-a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: S S.op_UnaryPlus(S x)) (OperationKind.Unary, Type: S) (Syntax: '+~!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: S S.op_OnesComplement(S x)) (OperationKind.Unary, Type: S) (Syntax: '~!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: S S.op_LogicalNot(S x)) (OperationKind.Unary, Type: S) (Syntax: '!-a')
Operand:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: S S.op_UnaryNegation(S x)) (OperationKind.Unary, Type: S) (Syntax: '-a')
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '++a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a++')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '--a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a--')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperatorOverloading_Checked_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x) { return new S('(' + ('+' + x.str) + ')'); }
public static S operator -(S x) { return new S('(' + ('-' + x.str) + ')'); }
public static S operator ~(S x) { return new S('(' + ('~' + x.str) + ')'); }
public static S operator !(S x) { return new S('(' + ('!' + x.str) + ')'); }
public static S operator ++(S x) { return new S('(' + x.str + '+' + '1' + ')'); }
public static S operator --(S x) { return new S('(' + x.str + '-' + '1' + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Method(S a)
/*<bind>*/{
checked
{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '++a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a++')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S x)) (OperationKind.Increment, Type: S) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '--a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Object value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'a--')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S x)) (OperationKind.Decrement, Type: S) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperator_IOperation()
{
string source = @"
using System;
class C
{
static void Method(int a)
/*<bind>*/{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IIncrementOrDecrementOperation (Postfix) (OperationKind.Decrement, Type: System.Int32) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestIncrementOperator_Checked_IOperation()
{
string source = @"
using System;
class C
{
static void Method(int a)
/*<bind>*/{
checked
{
Console.Write(++a);
Console.Write(a++);
Console.Write(--a);
Console.Write(a--);
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (4 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(++a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(++a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '++a')
IIncrementOrDecrementOperation (Prefix, Checked) (OperationKind.Increment, Type: System.Int32) (Syntax: '++a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a++);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a++)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a++')
IIncrementOrDecrementOperation (Postfix, Checked) (OperationKind.Increment, Type: System.Int32) (Syntax: 'a++')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(--a);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(--a)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '--a')
IIncrementOrDecrementOperation (Prefix, Checked) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--a')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Write(a--);')
Expression:
IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Write(a--)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a--')
IIncrementOrDecrementOperation (Postfix, Checked) (OperationKind.Decrement, Type: System.Int32) (Syntax: 'a--')
Target:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestBinaryOperatorOverloading()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public static S operator == (S x, S y) { return new S('(' + x.str + '=' + '=' + y.str + ')'); }
public static S operator != (S x, S y) { return new S('(' + x.str + '!' + '=' + y.str + ')'); }
public static S operator >= (S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); }
public static S operator <= (S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); }
public static S operator > (S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); }
public static S operator < (S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
S j = new S('j');
S k = new S('k');
S l = new S('l');
S m = new S('m');
S n = new S('n');
S o = new S('o');
S p = new S('p');
Console.WriteLine(
(a >> 10) + (b << 20) - c * d / e % f & g |
h ^ i == j != k < l > m <= o >= p);
}
}";
string output = @"(((((a>>10)+(b<<20))-(((c*d)/e)%f))&g)|(h^((i==j)!=((((k<l)>m)<=o)>=p))))";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestBinaryOperatorOverloading_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public static S operator ==(S x, S y) { return new S('(' + x.str + '=' + '=' + y.str + ')'); }
public static S operator !=(S x, S y) { return new S('(' + x.str + '!' + '=' + y.str + ')'); }
public static S operator >=(S x, S y) { return new S('(' + x.str + '>' + '=' + y.str + ')'); }
public static S operator <=(S x, S y) { return new S('(' + x.str + '<' + '=' + y.str + ')'); }
public static S operator >(S x, S y) { return new S('(' + x.str + '>' + y.str + ')'); }
public static S operator <(S x, S y) { return new S('(' + x.str + '<' + y.str + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
S j = new S('j');
S k = new S('k');
S l = new S('l');
S m = new S('m');
S n = new S('n');
S o = new S('o');
S p = new S('p');
Console.WriteLine(
/*<bind>*/(a >> 10) + (b << 20) - c * d / e % f & g |
h ^ i == j != k < l > m <= o >= p/*</bind>*/);
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... / e % f & g')
Left:
IBinaryOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + ... * d / e % f')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: '(a >> 10) + (b << 20)')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.Binary, Type: S) (Syntax: 'a >> 10')
Left:
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IBinaryOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.Binary, Type: S) (Syntax: 'b << 20')
Left:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: S) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
Right:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d / e % f')
Left:
IBinaryOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d / e')
Left:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'c * d')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: S) (Syntax: 'c')
Right:
ILocalReferenceOperation: d (OperationKind.LocalReference, Type: S) (Syntax: 'd')
Right:
ILocalReferenceOperation: e (OperationKind.LocalReference, Type: S) (Syntax: 'e')
Right:
ILocalReferenceOperation: f (OperationKind.LocalReference, Type: S) (Syntax: 'f')
Right:
ILocalReferenceOperation: g (OperationKind.LocalReference, Type: S) (Syntax: 'g')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'h ^ i == j ... m <= o >= p')
Left:
ILocalReferenceOperation: h (OperationKind.LocalReference, Type: S) (Syntax: 'h')
Right:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperatorMethod: S S.op_Inequality(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'i == j != k ... m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: S S.op_Equality(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'i == j')
Left:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: S) (Syntax: 'i')
Right:
ILocalReferenceOperation: j (OperationKind.LocalReference, Type: S) (Syntax: 'j')
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperatorMethod: S S.op_GreaterThanOrEqual(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m <= o >= p')
Left:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperatorMethod: S S.op_LessThanOrEqual(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m <= o')
Left:
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperatorMethod: S S.op_GreaterThan(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l > m')
Left:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperatorMethod: S S.op_LessThan(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'k < l')
Left:
ILocalReferenceOperation: k (OperationKind.LocalReference, Type: S) (Syntax: 'k')
Right:
ILocalReferenceOperation: l (OperationKind.LocalReference, Type: S) (Syntax: 'l')
Right:
ILocalReferenceOperation: m (OperationKind.LocalReference, Type: S) (Syntax: 'm')
Right:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: S) (Syntax: 'o')
Right:
ILocalReferenceOperation: p (OperationKind.LocalReference, Type: S) (Syntax: 'p')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0660: 'S' defines operator == or operator != but does not override Object.Equals(object o)
// struct S
Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "S").WithArguments("S").WithLocation(3, 8),
// CS0661: 'S' defines operator == or operator != but does not override Object.GetHashCode()
// struct S
Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "S").WithArguments("S").WithLocation(3, 8)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(657084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657084")]
[CompilerTrait(CompilerFeature.IOperation)]
public void DuplicateOperatorInSubclass()
{
string source = @"
class B
{
public static B operator +(C c, B b) { return null; }
}
class C : B
{
public static B operator +(C c, B b) { return null; }
}
class Test
{
public static void Main()
{
B b = /*<bind>*/new C() + new B()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'new C() + new B()')
Left:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Right:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0034: Operator '+' is ambiguous on operands of type 'C' and 'B'
// B b = /*<bind>*/new C() + new B()/*</bind>*/;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "new C() + new B()").WithArguments("+", "C", "B").WithLocation(16, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Enums_Dynamic_Unambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
using System.Collections.Generic;
class C<T>
{
enum E { A }
public void M()
{
var eq1 = C<dynamic>.E.A == C<object>.E.A;
var eq2 = C<object>.E.A == C<dynamic>.E.A;
var eq3 = C<Dictionary<object, dynamic>>.E.A == C<Dictionary<dynamic, object>>.E.A;
var neq1 = C<dynamic>.E.A != C<object>.E.A;
var neq2 = C<object>.E.A != C<dynamic>.E.A;
var neq3 = C<Dictionary<object, dynamic>>.E.A != C<Dictionary<dynamic, object>>.E.A;
var lt1 = C<dynamic>.E.A < C<object>.E.A;
var lt2 = C<object>.E.A < C<dynamic>.E.A;
var lt3 = C<Dictionary<object, dynamic>>.E.A < C<Dictionary<dynamic, object>>.E.A;
var lte1 = C<dynamic>.E.A <= C<object>.E.A;
var lte2 = C<object>.E.A <= C<dynamic>.E.A;
var lte3 = C<Dictionary<object, dynamic>>.E.A <= C<Dictionary<dynamic, object>>.E.A;
var gt1 = C<dynamic>.E.A > C<object>.E.A;
var gt2 = C<object>.E.A > C<dynamic>.E.A;
var gt3 = C<Dictionary<object, dynamic>>.E.A > C<Dictionary<dynamic, object>>.E.A;
var gte1 = C<dynamic>.E.A >= C<object>.E.A;
var gte2 = C<object>.E.A >= C<dynamic>.E.A;
var gte3 = C<Dictionary<object, dynamic>>.E.A >= C<Dictionary<dynamic, object>>.E.A;
var sub1 = C<dynamic>.E.A - C<object>.E.A;
var sub2 = C<object>.E.A - C<dynamic>.E.A;
var sub3 = C<Dictionary<object, dynamic>>.E.A - C<Dictionary<dynamic, object>>.E.A;
var subu1 = C<dynamic>.E.A - 1;
var subu3 = C<Dictionary<object, dynamic>>.E.A - 1;
var usub1 = 1 - C<dynamic>.E.A;
var usub3 = 1 - C<Dictionary<object, dynamic>>.E.A;
var addu1 = C<dynamic>.E.A + 1;
var addu3 = C<Dictionary<object, dynamic>>.E.A + 1;
var uadd1 = 1 + C<dynamic>.E.A;
var uadd3 = 1 + C<Dictionary<object, dynamic>>.E.A;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics();
}
[Fact, WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
[CompilerTrait(CompilerFeature.IOperation)]
public void TestBinaryOperatorOverloading_Enums_Dynamic_Ambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
enum E { A }
public void M()
{
var and = C<dynamic>.E.A & C<object>.E.A;
var or = C<dynamic>.E.A | C<object>.E.A;
var xor = C<dynamic>.E.A ^ C<object>.E.A;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (10,19): error CS0034: Operator '&' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A & C<object>.E.A").WithArguments("&", "C<dynamic>.E", "C<object>.E"),
// (11,18): error CS0034: Operator '|' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A | C<object>.E.A").WithArguments("|", "C<dynamic>.E", "C<object>.E"),
// (12,19): error CS0034: Operator '^' is ambiguous on operands of type 'C<dynamic>.E' and 'C<object>.E'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "C<dynamic>.E.A ^ C<object>.E.A").WithArguments("^", "C<dynamic>.E", "C<object>.E"));
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Unambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
delegate void A<U, V>(U u, V v);
C<dynamic>.A<object, object> d1 = null;
C<object>.A<object, object> d2 = null;
C<dynamic>.A<object, dynamic> d3 = null;
C<object>.A<dynamic, object> d4 = null;
public void M()
{
var eq1 = d1 == d2;
var eq2 = d1 == d3;
var eq3 = d1 == d4;
var eq4 = d2 == d3;
var neq1 = d1 != d2;
var neq2 = d1 != d3;
var neq3 = d1 != d4;
var neq4 = d2 != d3;
}
}
";
// Dev11 reports error CS0034: Operator '...' is ambiguous on operands ... and ... for all combinations
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics();
}
[Fact]
public void TestBinaryOperatorOverloading_UserDefined_Dynamic_Unambiguous()
{
string source = @"
class D<T>
{
public class C
{
public static int operator +(C x, C y) { return 1; }
}
}
class X
{
static void Main()
{
var x = new D<object>.C();
var y = new D<dynamic>.C();
var z = /*<bind>*/x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 D<System.Object>.C.op_Addition(D<System.Object>.C x, D<System.Object>.C y)) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: D<System.Object>.C) (Syntax: 'x')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: D<System.Object>.C, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: D<dynamic>.C) (Syntax: 'y')
";
// Dev11 reports error CS0121: The call is ambiguous between the following methods or properties:
// 'D<object>.C.operator+(D<object>.C, D<object>.C)' and 'D<dynamic>.C.operator +(D<dynamic>.C, D<dynamic>.C)'
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void TestBinaryOperatorOverloading_UserDefined_Dynamic_Ambiguous()
{
string source = @"
class D<T>
{
public class C
{
public static C operator +(C x, C y) { return null; }
}
}
class X
{
static void Main()
{
var x = new D<object>.C();
var y = new D<dynamic>.C();
var z = /*<bind>*/x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: D<System.Object>.C, IsInvalid) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: D<dynamic>.C, IsInvalid) (Syntax: 'y')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0034: Operator '+' is ambiguous on operands of type 'D<object>.C' and 'D<dynamic>.C'
// var z = /*<bind>*/x + y/*</bind>*/;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "D<object>.C", "D<dynamic>.C").WithLocation(16, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Ambiguous()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
class C<T>
{
delegate void A<U, V>(U u, V v);
C<dynamic>.A<object, object> d1 = null;
C<object>.A<object, object> d2 = null;
C<dynamic>.A<object, dynamic> d3 = null;
C<object>.A<dynamic, object> d4 = null;
public void M()
{
var add1 = d1 + d2;
var add2 = d1 + d3;
var add3 = d1 + d4;
var add4 = d2 + d3;
var sub1 = d1 - d2;
var sub2 = d1 - d3;
var sub3 = d1 - d4;
var sub4 = d2 - d3;
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (17,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<object, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d2").WithArguments("+", "C<dynamic>.A<object, object>", "C<object>.A<object, object>"),
// (18,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d3").WithArguments("+", "C<dynamic>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (19,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<dynamic, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 + d4").WithArguments("+", "C<dynamic>.A<object, object>", "C<object>.A<dynamic, object>"),
// (20,20): error CS0034: Operator '+' is ambiguous on operands of type 'C<object>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d2 + d3").WithArguments("+", "C<object>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (22,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<object, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d2").WithArguments("-", "C<dynamic>.A<object, object>", "C<object>.A<object, object>"),
// (23,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d3").WithArguments("-", "C<dynamic>.A<object, object>", "C<dynamic>.A<object, dynamic>"),
// (24,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<dynamic>.A<object, object>' and 'C<object>.A<dynamic, object>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d1 - d4").WithArguments("-", "C<dynamic>.A<object, object>", "C<object>.A<dynamic, object>"),
// (25,20): error CS0034: Operator '-' is ambiguous on operands of type 'C<object>.A<object, object>' and 'C<dynamic>.A<object, dynamic>'
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "d2 - d3").WithArguments("-", "C<object>.A<object, object>", "C<dynamic>.A<object, dynamic>"));
}
[Fact]
[WorkItem(624270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624270"), WorkItem(624274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624274")]
public void TestBinaryOperatorOverloading_Delegates_Dynamic_Ambiguous_Inference()
{
string source = @"
using System;
class Program
{
static void Main()
{
Action<object> a = null;
Goo(c => c == a);
}
static void Goo(Func<Action<object>, IComparable> x) { }
static void Goo(Func<Action<dynamic>, IConvertible> x) { }
}
";
// Dev11 considers Action<object> == Action<dynamic> ambiguous and thus chooses Goo(Func<Action<object>, IComparable>) overload.
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Goo(System.Func<System.Action<object>, System.IComparable>)' and 'Program.Goo(System.Func<System.Action<dynamic>, System.IConvertible>)'
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("Program.Goo(System.Func<System.Action<object>, System.IComparable>)", "Program.Goo(System.Func<System.Action<dynamic>, System.IConvertible>)"));
}
[Fact]
public void TestBinaryOperatorOverloading_Pointers_Dynamic()
{
string source = @"
#pragma warning disable 219 // The variable is assigned but its value is never used
using System.Collections.Generic;
unsafe class C<T>
{
enum E { A }
public void M()
{
var o = C<object>.E.A;
var d = C<dynamic>.E.A;
var dict1 = C<Dictionary<object, dynamic>>.E.A;
var dict2 = C<Dictionary<dynamic, object>>.E.A;
var eq1 = &o == &d;
var eq2 = &d == &o;
var eq3 = &dict1 == &dict2;
var eq4 = &dict2 == &dict1;
var neq1 = &o != &d;
var neq2 = &d != &o;
var neq3 = &dict1 != &dict2;
var neq4 = &dict2 != &dict1;
var sub1 = &o - &d;
var sub2 = &d - &o;
var sub3 = &dict1 - &dict2;
var sub4 = &dict2 - &dict1;
var subi1 = &o - 1;
var subi2 = &d - 1;
var subi3 = &dict1 - 1;
var subi4 = &dict2 - 1;
var addi1 = &o + 1;
var addi2 = &d + 1;
var addi3 = &dict1 + 1;
var addi4 = &dict2 + 1;
var iadd1 = 1 + &o;
var iadd2 = 1 + &d;
var iadd3 = 1 + &dict1;
var iadd4 = 1 + &dict2;
}
}
";
// Dev11 reports "error CS0034: Operator '-' is ambiguous on operands ... and ..." for all ptr - ptr
CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
}
[Fact]
public void TestOverloadResolutionTiebreakers()
{
string source = @"
using System;
struct S
{
public static bool operator == (S x, S y) { return true; }
public static bool operator != (S x, S y) { return false; }
public static bool operator == (S? x, S? y) { return true; }
public static bool operator != (S? x, S? y) { return false; }
public override bool Equals(object s) { return true; }
public override int GetHashCode() { return 0; }
public override string ToString() { return this.str; }
}
class X<T>
{
public static int operator +(X<T> x, int y) { return 0; }
public static int operator +(X<T> x, T y) { return 0; }
}
struct Q<U> where U : struct
{
public static int operator +(Q<U> x, int y) { return 0; }
public static int? operator +(Q<U>? x, U? y) { return 1; }
}
class C
{
static void M()
{
S s1 = new S();
S s2 = new S();
S? s3 = new S();
S? s4 = null;
X<int> xint = null;
int x = xint + 123; //-UserDefinedAddition
// In this case the native compiler and the spec disagree. Roslyn implements the spec.
// The tiebreaker is supposed to check for *specificity* first, and then *liftedness*.
// The native compiler eliminates the lifted operator even if it is more specific:
int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
// All of these go to a user-defined equality operator;
// the lifted form is always worse than the unlifted form,
// and the user-defined form is always better than turning
// '== null' into a call to HasValue().
bool[] b =
{
s1 == s2, //-UserDefinedEqual
s1 == s3, //-UserDefinedEqual
s1 == null, //-UserDefinedEqual
s3 == s1, //-UserDefinedEqual
s3 == s4, //-UserDefinedEqual
s3 == null, //-UserDefinedEqual
null == s1, //-UserDefinedEqual
null == s3 //-UserDefinedEqual
};
}
}";
TestOperatorKinds(source);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestOverloadResolutionTiebreakers_IOperation()
{
string source = @"
using System;
struct S
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return false; }
public static bool operator ==(S? x, S? y) { return true; }
public static bool operator !=(S? x, S? y) { return false; }
public override bool Equals(object s) { return true; }
public override int GetHashCode() { return 0; }
public override string ToString() { return this.str; }
}
class X<T>
{
public static int operator +(X<T> x, int y) { return 0; }
public static int operator +(X<T> x, T y) { return 0; }
}
struct Q<U> where U : struct
{
public static int operator +(Q<U> x, int y) { return 0; }
public static int? operator +(Q<U>? x, U? y) { return 1; }
}
class C
{
static void M(S s1, S s2, S? s3, S? s4, X<int> xint)
/*<bind>*/{
int x = xint + 123; //-UserDefinedAddition
// In this case the native compiler and the spec disagree. Roslyn implements the spec.
// The tiebreaker is supposed to check for *specificity* first, and then *liftedness*.
// The native compiler eliminates the lifted operator even if it is more specific:
int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
// All of these go to a user-defined equality operator;
// the lifted form is always worse than the unlifted form,
// and the user-defined form is always better than turning
// '== null' into a call to HasValue().
bool[] b =
{
s1 == s2, //-UserDefinedEqual
s1 == s3, //-UserDefinedEqual
s1 == null, //-UserDefinedEqual
s3 == s1, //-UserDefinedEqual
s3 == s4, //-UserDefinedEqual
s3 == null, //-UserDefinedEqual
null == s1, //-UserDefinedEqual
null == s3 //-UserDefinedEqual
};
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (3 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 x
Local_2: System.Int32? q
Local_3: System.Boolean[] b
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int x = xint + 123;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int x = xint + 123')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = xint + 123')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= xint + 123')
IBinaryOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 X<System.Int32>.op_Addition(X<System.Int32> x, System.Int32 y)) (OperationKind.Binary, Type: System.Int32) (Syntax: 'xint + 123')
Left:
IParameterReferenceOperation: xint (OperationKind.ParameterReference, Type: X<System.Int32>) (Syntax: 'xint')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123')
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int? q = ne ... new int?();')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int? q = ne ... new int?()')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32? q) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'q = new Q<i ... new int?()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new Q<int ... new int?()')
IBinaryOperation (BinaryOperatorKind.Add, IsLifted) (OperatorMethod: System.Int32 Q<System.Int32>.op_Addition(Q<System.Int32> x, System.Int32 y)) (OperationKind.Binary, Type: System.Int32?) (Syntax: 'new Q<int>? ... new int?()')
Left:
IObjectCreationOperation (Constructor: Q<System.Int32>?..ctor()) (OperationKind.ObjectCreation, Type: Q<System.Int32>?) (Syntax: 'new Q<int>?()')
Arguments(0)
Initializer:
null
Right:
IObjectCreationOperation (Constructor: System.Int32?..ctor()) (OperationKind.ObjectCreation, Type: System.Int32?) (Syntax: 'new int?()')
Arguments(0)
Initializer:
null
Initializer:
null
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'bool[] b = ... };')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'bool[] b = ... }')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Boolean[] b) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b = ... }')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ... }')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Boolean[], IsImplicit) (Syntax: '{ ... }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 8, IsImplicit) (Syntax: '{ ... }')
Initializer:
IArrayInitializerOperation (8 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ ... }')
Element Values(8):
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S x, S y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == s2')
Left:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S) (Syntax: 's2')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == s3')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's1 == null')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == s1')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == s4')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IParameterReferenceOperation: s4 (OperationKind.ParameterReference, Type: S?) (Syntax: 's4')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's3 == null')
Left:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'null == s1')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IBinaryOperation (BinaryOperatorKind.Equals) (OperatorMethod: System.Boolean S.op_Equality(S? x, S? y)) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'null == s3')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, Constant: null, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Right:
IParameterReferenceOperation: s3 (OperationKind.ParameterReference, Type: S?) (Syntax: 's3')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0458: The result of the expression is always 'null' of type 'int?'
// int? q = new Q<int>?() + new int?(); //-LiftedUserDefinedAddition
Diagnostic(ErrorCode.WRN_AlwaysNull, "new Q<int>?() + new int?()").WithArguments("int?").WithLocation(37, 18),
// CS1061: 'S' does not contain a definition for 'str' and no extension method 'str' accepting a first argument of type 'S' could be found (are you missing a using directive or an assembly reference?)
// public override string ToString() { return this.str; }
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "str").WithArguments("S", "str").WithLocation(11, 53)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUserDefinedCompoundAssignment()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator + (S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator - (S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator % (S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator / (S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator * (S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator & (S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator | (S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^ (S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator << (S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >> (S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main()
{
S a = new S('a');
S b = new S('b');
S c = new S('c');
S d = new S('d');
S e = new S('e');
S f = new S('f');
S g = new S('g');
S h = new S('h');
S i = new S('i');
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
Console.WriteLine(a);
}
}";
string output = @"((((((((((a+b)-c)*d)/e)%f)<<10)>>20)&g)|h)^i)";
CompileAndVerify(source: source, expectedOutput: output);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedCompoundAssignment_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main(S a, S b, S c, S d, S e, S f, S g, S h, S i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: S) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: S) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: S) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: S) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: S) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: S) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: S) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: S) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedCompoundAssignment_Checked_IOperation()
{
string source = @"
using System;
struct S
{
private string str;
public S(char chr) { this.str = chr.ToString(); }
public S(string str) { this.str = str; }
public static S operator +(S x, S y) { return new S('(' + x.str + '+' + y.str + ')'); }
public static S operator -(S x, S y) { return new S('(' + x.str + '-' + y.str + ')'); }
public static S operator %(S x, S y) { return new S('(' + x.str + '%' + y.str + ')'); }
public static S operator /(S x, S y) { return new S('(' + x.str + '/' + y.str + ')'); }
public static S operator *(S x, S y) { return new S('(' + x.str + '*' + y.str + ')'); }
public static S operator &(S x, S y) { return new S('(' + x.str + '&' + y.str + ')'); }
public static S operator |(S x, S y) { return new S('(' + x.str + '|' + y.str + ')'); }
public static S operator ^(S x, S y) { return new S('(' + x.str + '^' + y.str + ')'); }
public static S operator <<(S x, int y) { return new S('(' + x.str + '<' + '<' + y.ToString() + ')'); }
public static S operator >>(S x, int y) { return new S('(' + x.str + '>' + '>' + y.ToString() + ')'); }
public override string ToString() { return this.str; }
}
class C
{
static void Main(S a, S b, S c, S d, S e, S f, S g, S h, S i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: S S.op_Addition(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: S) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperatorMethod: S S.op_Subtraction(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: S) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperatorMethod: S S.op_Multiply(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: S) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperatorMethod: S S.op_Division(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: S) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperatorMethod: S S.op_Modulus(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: S) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperatorMethod: S S.op_LeftShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperatorMethod: S S.op_RightShift(S x, System.Int32 y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: S) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: S) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperatorMethod: S S.op_ExclusiveOr(S x, S y)) (OperationKind.CompoundAssignment, Type: S) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: S) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: S) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestCompoundAssignment_IOperation()
{
string source = @"
class C
{
static void M(int a, int b, int c, int d, int e, int f, int g, int h, int i)
/*<bind>*/{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(21723, "https://github.com/dotnet/roslyn/issues/21723")]
public void TestCompoundLiftedAssignment_IOperation()
{
string source = @"
class C
{
static void M(int a, int? b)
{
/*<bind>*/a += b/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add, IsLifted) (OperationKind.CompoundAssignment, Type: System.Int32, IsInvalid) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'b')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
// /*<bind>*/a += b/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a += b").WithArguments("int?", "int").WithLocation(6, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestCompoundAssignment_Checked_IOperation()
{
string source = @"
class C
{
static void M(int a, int b, int c, int d, int e, int f, int g, int h, int i)
/*<bind>*/{
checked
{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide, Checked) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestCompoundAssignment_Unchecked_IOperation()
{
string source = @"
class C
{
static void M(int a, int b, int c, int d, int e, int f, int g, int h, int i)
/*<bind>*/{
unchecked
{
a += b;
a -= c;
a *= d;
a /= e;
a %= f;
a <<= 10;
a >>= 20;
a &= g;
a |= h;
a ^= i;
}
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IBlockOperation (10 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a += b;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a += b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a -= c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a -= c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a *= d;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a *= d')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a /= e;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a /= e')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'e')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a %= f;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a %= f')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'f')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a <<= 10;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a <<= 10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a >>= 20;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a >>= 20')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a &= g;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a &= g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'g')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a |= h;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a |= h')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: h (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'h')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a ^= i;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a ^= i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUserDefinedBinaryOperatorOverloadResolution()
{
TestOperatorKinds(@"
using System;
struct S
{
public static int operator + (S x1, S x2) { return 1; }
public static int? operator - (S x1, S? x2) { return 1; }
public static S operator & (S x1, S x2) { return x1; }
public static bool operator true(S? x1) { return true; }
public static bool operator false(S? x1) { return false; }
}
class B
{
public static bool operator ==(B b1, B b2) { return true; }
public static bool operator !=(B b1, B b2) { return true; }
}
class D : B {}
class C
{
static void M()
{
bool f;
B b = null;
D d = null;
S s1 = new S();
S? s2 = s1;
int i1;
int? i2;
i1 = s1 + s1; //-UserDefinedAddition
i2 = s1 + s2; //-LiftedUserDefinedAddition
i2 = s2 + s1; //-LiftedUserDefinedAddition
i2 = s2 + s2; //-LiftedUserDefinedAddition
// No lifted form.
i2 = s1 - s1; //-UserDefinedSubtraction
i2 = s1 - s2; //-UserDefinedSubtraction
f = b == b; //-UserDefinedEqual
f = b == d; //-UserDefinedEqual
f = d == b; //-UserDefinedEqual
f = d == d; //-UserDefinedEqual
s1 = s1 & s1; //-UserDefinedAnd
s2 = s2 & s1; //-LiftedUserDefinedAnd
s2 = s1 & s2; //-LiftedUserDefinedAnd
s2 = s2 & s2; //-LiftedUserDefinedAnd
// No lifted form.
s1 = s1 && s1; //-LogicalUserDefinedAnd
// UNDONE: More tests
}
}");
}
[Fact]
public void TestUserDefinedUnaryOperatorOverloadResolution()
{
TestOperatorKinds(@"
using System;
struct S
{
public static int operator +(S s) { return 1; }
public static int operator -(S? s) { return 2; }
public static int operator !(S s) { return 3; }
public static int operator ~(S s) { return 4; }
public static S operator ++(S s) { return s; }
public static S operator --(S? s) { return (S)s; }
}
class C
{
static void M()
{
S s1 = new S();
S? s2 = s1;
int i1;
int? i2;
i1 = +s1; //-UserDefinedUnaryPlus
i2 = +s2; //-LiftedUserDefinedUnaryPlus
// No lifted form.
i1 = -s1; //-UserDefinedUnaryMinus
i1 = -s2; //-UserDefinedUnaryMinus
i1 = !s1; //-UserDefinedLogicalNegation
i2 = !s2; //-LiftedUserDefinedLogicalNegation
i1 = ~s1; //-UserDefinedBitwiseComplement
i2 = ~s2; //-LiftedUserDefinedBitwiseComplement
s1++; //-UserDefinedPostfixIncrement
s2++; //-LiftedUserDefinedPostfixIncrement
++s1; //-UserDefinedPrefixIncrement
++s2; //-LiftedUserDefinedPrefixIncrement
// No lifted form
s1--; //-UserDefinedPostfixDecrement
s2--; //-UserDefinedPostfixDecrement
}
}");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TestUserDefinedUnaryOperatorOverloadResolution_IOperation()
{
string source = @"
using System;
struct S
{
public static int operator +(S s) { return 1; }
public static int operator -(S? s) { return 2; }
public static int operator !(S s) { return 3; }
public static int operator ~(S s) { return 4; }
public static S operator ++(S s) { return s; }
public static S operator --(S? s) { return (S)s; }
}
class C
{
static void M(S s1, S? s2, int i1, int? i2)
/*<bind>*/{
i1 = +s1; //-UserDefinedUnaryPlus
i2 = +s2; //-LiftedUserDefinedUnaryPlus
// No lifted form.
i1 = -s1; //-UserDefinedUnaryMinus
i1 = -s2; //-UserDefinedUnaryMinus
i1 = !s1; //-UserDefinedLogicalNegation
i2 = !s2; //-LiftedUserDefinedLogicalNegation
i1 = ~s1; //-UserDefinedBitwiseComplement
i2 = ~s2; //-LiftedUserDefinedBitwiseComplement
s1++; //-UserDefinedPostfixIncrement
s2++; //-LiftedUserDefinedPostfixIncrement
++s1; //-UserDefinedPrefixIncrement
++s2; //-LiftedUserDefinedPrefixIncrement
// No lifted form
s1--; //-UserDefinedPostfixDecrement
s2--; //-UserDefinedPostfixDecrement
}/*</bind>*/
}
";
string expectedOperationTree = @"
IBlockOperation (14 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = +s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = +s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: System.Int32 S.op_UnaryPlus(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '+s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = +s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = +s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.Plus, IsLifted) (OperatorMethod: System.Int32 S.op_UnaryPlus(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '+s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = -s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = -s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: System.Int32 S.op_UnaryNegation(S? s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '-s1')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: S?, IsImplicit) (Syntax: 's1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = -s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = -s2')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: System.Int32 S.op_UnaryNegation(S? s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '-s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = !s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = !s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: System.Int32 S.op_LogicalNot(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '!s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = !s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = !s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.Not, IsLifted) (OperatorMethod: System.Int32 S.op_LogicalNot(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '!s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i1 = ~s1;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i1 = ~s1')
Left:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Right:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: System.Int32 S.op_OnesComplement(S s)) (OperationKind.Unary, Type: System.Int32) (Syntax: '~s1')
Operand:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i2 = ~s2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'i2 = ~s2')
Left:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i2')
Right:
IUnaryOperation (UnaryOperatorKind.BitwiseNegation, IsLifted) (OperatorMethod: System.Int32 S.op_OnesComplement(S s)) (OperationKind.Unary, Type: System.Int32?) (Syntax: '~s2')
Operand:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's1++;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S) (Syntax: 's1++')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's2++;')
Expression:
IIncrementOrDecrementOperation (Postfix, IsLifted) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S?) (Syntax: 's2++')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '++s1;')
Expression:
IIncrementOrDecrementOperation (Prefix) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S) (Syntax: '++s1')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '++s2;')
Expression:
IIncrementOrDecrementOperation (Prefix, IsLifted) (OperatorMethod: S S.op_Increment(S s)) (OperationKind.Increment, Type: S?) (Syntax: '++s2')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's1--;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S? s)) (OperationKind.Decrement, Type: S) (Syntax: 's1--')
Target:
IParameterReferenceOperation: s1 (OperationKind.ParameterReference, Type: S) (Syntax: 's1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 's2--;')
Expression:
IIncrementOrDecrementOperation (Postfix) (OperatorMethod: S S.op_Decrement(S? s)) (OperationKind.Decrement, Type: S?) (Syntax: 's2--')
Target:
IParameterReferenceOperation: s2 (OperationKind.ParameterReference, Type: S?) (Syntax: 's2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type
// public static S operator --(S? s) { return (S)s; }
Diagnostic(ErrorCode.ERR_BadIncDecRetType, "--").WithLocation(10, 30)
};
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TestUnaryOperatorOverloadingErrors()
{
var source = @"
class C
{
// UNDONE: Write tests for the rest of them
void M(bool b)
{
if(!1) {}
b++;
error++;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,12): error CS0023: Operator '!' cannot be applied to operand of type 'int'
// if(!1) {}
Diagnostic(ErrorCode.ERR_BadUnaryOp, "!1").WithArguments("!", "int").WithLocation(7, 12),
// (8,9): error CS0023: Operator '++' cannot be applied to operand of type 'bool'
// b++;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "b++").WithArguments("++", "bool").WithLocation(8, 9),
// (9,9): error CS0103: The name 'error' does not exist in the current context
// error++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var negOne = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("!1", negOne.ToString());
var type1 = model.GetTypeInfo(negOne).Type;
Assert.Equal("?", type1.ToTestDisplayString());
Assert.True(type1.IsErrorType());
var boolPlusPlus = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ElementAt(0);
Assert.Equal("b++", boolPlusPlus.ToString());
var type2 = model.GetTypeInfo(boolPlusPlus).Type;
Assert.Equal("?", type2.ToTestDisplayString());
Assert.True(type2.IsErrorType());
var errorPlusPlus = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ElementAt(1);
Assert.Equal("error++", errorPlusPlus.ToString());
var type3 = model.GetTypeInfo(errorPlusPlus).Type;
Assert.Equal("?", type3.ToTestDisplayString());
Assert.True(type3.IsErrorType());
}
[Fact]
public void TestBinaryOperatorOverloadingErrors()
{
// The native compiler and Roslyn report slightly different errors here.
// The native compiler reports CS0019 when attempting to add or compare long and ulong:
// that is "operator cannot be applied to operands of type long and ulong". This is
// correct but not as specific as it could be; the error is actually because overload
// resolution is ambiguous. The double + double --> double, float + float --> float
// and decimal + decimal --> decimal operators are all applicable but overload resolution
// finds that this set of applicable operators is ambiguous; float is better than double,
// but neither float nor decimal is better than the other.
//
// Roslyn produces the more accurate error; this is an ambiguity.
//
// Comparing string and exception is not ambiguous; the only applicable operator
// is the reference equality operator, and it requires that its operand types be
// convertible to each other.
string source = @"
class C
{
bool N() { return false; }
void M()
{
long i64 = 1;
ulong ui64 = 1;
System.String s1 = null;
System.Exception ex1 = null;
object o1 = i64 + ui64; // CS0034
bool b1 = i64 == ui64; // CS0034
bool b2 = s1 == ex1; // CS0019
bool b3 = (object)s1 == ex1; // legal!
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,21): error CS0034: Operator '+' is ambiguous on operands of type 'long' and 'ulong'
// object o1 = i64 + ui64; // CS0034
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i64 + ui64").WithArguments("+", "long", "ulong"),
// (12,19): error CS0034: Operator '==' is ambiguous on operands of type 'long' and 'ulong'
// bool b1 = i64 == ui64; // CS0034
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i64 == ui64").WithArguments("==", "long", "ulong"),
// (13,19): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'System.Exception'
// bool b2 = s1 == ex1; // CS0019
Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 == ex1").WithArguments("==", "string", "System.Exception"));
}
[Fact]
public void TestCompoundOperatorErrors()
{
var source = @"
class C
{
// UNDONE: Add more error cases
class D : C {}
public static C operator + (C c1, C c2) { return c1; }
public int ReadOnly { get { return 0; } }
public int WriteOnly { set { } }
void M()
{
C c = new C();
D d = new D();
c.ReadOnly += 1;
c.WriteOnly += 1;
int i32 = 1;
long i64 = 1;
// If we have x += y and the + is a built-in operator then
// the result must be *explicitly* convertible to x, and y
// must be *implicitly* convertible to x.
//
// If the + is a user-defined operator then the result must
// be *implicitly* convertible to x, and y need not have
// any relationship with x.
// Overload resolution resolves this as long + long --> long.
// The result is explicitly convertible to int, but the right-hand
// side is not, so this is an error.
i32 += i64;
// In the user-defined conversion, the result of the addition must
// be *implicitly* convertible to the left hand side:
d += c;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (17,9): error CS0200: Property or indexer 'C.ReadOnly' cannot be assigned to -- it is read only
// c.ReadOnly += 1;
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.ReadOnly").WithArguments("C.ReadOnly").WithLocation(17, 9),
// (18,9): error CS0154: The property or indexer 'C.WriteOnly' cannot be used in this context because it lacks the get accessor
// c.WriteOnly += 1;
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.WriteOnly").WithArguments("C.WriteOnly").WithLocation(18, 9),
// (34,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
// i32 += i64;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "i32 += i64").WithArguments("long", "int").WithLocation(34, 9),
// (39,9): error CS0266: Cannot implicitly convert type 'C' to 'C.D'. An explicit conversion exists (are you missing a cast?)
// d += c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "d += c").WithArguments("C", "C.D").WithLocation(39, 9));
}
[Fact]
public void TestOperatorOverloadResolution()
{
// UNDONE: User-defined operators
// UNDONE: TestOverloadResolution(GenerateTest(PostfixIncrementTemplate, "++", "PostfixIncrement"));
// UNDONE: TestOverloadResolution(GenerateTest(PostfixIncrementTemplate, "--", "PostfixDecrement"));
TestOperatorKinds(GenerateTest(PrefixIncrementTemplate, "++", "PrefixIncrement"));
TestOperatorKinds(GenerateTest(PrefixIncrementTemplate, "--", "PrefixDecrement"));
// UNDONE: Pointer ++ --
TestOperatorKinds(UnaryPlus);
TestOperatorKinds(UnaryMinus);
TestOperatorKinds(LogicalNegation);
TestOperatorKinds(BitwiseComplement);
TestOperatorKinds(EnumAddition);
TestOperatorKinds(StringAddition);
TestOperatorKinds(DelegateAddition);
// UNDONE: Pointer addition
TestOperatorKinds(EnumSubtraction);
TestOperatorKinds(DelegateSubtraction);
// UNDONE: Pointer subtraction
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "+", "Addition"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "-", "Subtraction"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "*", "Multiplication"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "/", "Division"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "%", "Remainder"));
TestOperatorKinds(GenerateTest(ShiftTemplate, "<<", "LeftShift"));
TestOperatorKinds(GenerateTest(ShiftTemplate, ">>", "RightShift"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "==", "Equal"));
TestOperatorKinds(GenerateTest(ArithmeticTemplate, "!=", "NotEqual"));
TestOperatorKinds(GenerateTest(EqualityTemplate, "!=", "NotEqual"));
TestOperatorKinds(GenerateTest(EqualityTemplate, "!=", "NotEqual"));
// UNDONE: Pointer equality
TestOperatorKinds(GenerateTest(ComparisonTemplate, ">", "GreaterThan"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, ">=", "GreaterThanOrEqual"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, "<", "LessThan"));
TestOperatorKinds(GenerateTest(ComparisonTemplate, "<=", "LessThanOrEqual"));
TestOperatorKinds(GenerateTest(LogicTemplate, "^", "Xor"));
TestOperatorKinds(GenerateTest(LogicTemplate, "&", "And"));
TestOperatorKinds(GenerateTest(LogicTemplate, "|", "Or"));
TestOperatorKinds(GenerateTest(ShortCircuitTemplate, "&&", "And"));
TestOperatorKinds(GenerateTest(ShortCircuitTemplate, "||", "Or"));
}
[Fact]
public void TestEnumOperatorOverloadResolution()
{
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "^", "Xor"));
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "&", "And"));
TestOperatorKinds(GenerateTest(EnumLogicTemplate, "|", "Or"));
}
[Fact]
public void TestConstantOperatorOverloadResolution()
{
string code =
@"class C
{
static void F(object o) { }
static void M()
{
const short ci16 = 1;
uint u32 = 1;
F(u32 + 1); //-UIntAddition
F(2 + u32); //-UIntAddition
F(u32 + ci16); //-LongAddition
F(u32 + int.MaxValue); //-UIntAddition
F(u32 + (-1)); //-LongAddition
//-IntUnaryMinus
F(u32 + long.MaxValue); //-LongAddition
int i32 = 2;
F(i32 + 1); //-IntAddition
F(2 + i32); //-IntAddition
F(i32 + ci16); //-IntAddition
F(i32 + int.MaxValue); //-IntAddition
F(i32 + (-1)); //-IntAddition
//-IntUnaryMinus
}
}
";
TestOperatorKinds(code);
}
private void TestBoundTree(string source, System.Func<IEnumerable<KeyValuePair<TreeDumperNode, TreeDumperNode>>, IEnumerable<string>> query)
{
// The mechanism of this test is: we build the bound tree for the code passed in and then extract
// from it the nodes that describe the operators. We then compare the description of
// the operators given to the comment that follows the use of the operator.
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
var diagnostics = new DiagnosticBag();
var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics));
var tree = BoundTreeDumperNodeProducer.MakeTree(block);
var results = string.Join("\n",
query(tree.PreorderTraversal())
.ToArray());
var expected = string.Join("\n", source
.Split(new[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries)
.Where(x => x.Contains("//-"))
.Select(x => x.Substring(x.IndexOf("//-", StringComparison.Ordinal) + 3).Trim())
.ToArray());
Assert.Equal(expected, results);
}
private void TestOperatorKinds(string source)
{
// The mechanism of this test is: we build the bound tree for the code passed in and then extract
// from it the nodes that describe the operators. We then compare the description of
// the operators given to the comment that follows the use of the operator.
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "operatorKind"
where node.Value != null
select node.Value.ToString());
}
private void TestCompoundAssignment(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node != null && (node.Text == "eventAssignmentOperator" || node.Text == "compoundAssignmentOperator")
select string.Join(" ", from child in node.Children
where child.Text == "@operator" ||
child.Text == "isAddition" ||
child.Text == "isDynamic" ||
child.Text == "leftConversion" ||
child.Text == "finalConversion"
select child.Text + ": " + (child.Text == "@operator" ? ((BinaryOperatorSignature)child.Value).Kind.ToString() : child.Value.ToString())));
}
private void TestTypes(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "type"
select edge.Key.Text + ": " + (node.Value != null ? node.Value.ToString() : "<null>"));
}
private static string FormatTypeArgumentList(ImmutableArray<TypeWithAnnotations>? arguments)
{
if (arguments == null || arguments.Value.IsEmpty)
{
return "";
}
string s = "<";
for (int i = 0; i < arguments.Value.Length; ++i)
{
if (i != 0)
{
s += ", ";
}
s += arguments.Value[i].Type.ToString();
}
return s + ">";
}
private void TestDynamicMemberAccessCore(string source)
{
TestBoundTree(source, edges =>
from edge in edges
let node = edge.Value
where node.Text == "dynamicMemberAccess"
let name = node["name"]
let typeArguments = node["typeArgumentsOpt"].Value as ImmutableArray<TypeWithAnnotations>?
select name.Value.ToString() + FormatTypeArgumentList(typeArguments));
}
private static string GenerateTest(string template, string op, string opkind)
{
string result = template.Replace("OPERATOR", op);
result = result.Replace("KIND", opkind);
return result;
}
#region "Constant String"
private const string Prefix = @"
class C
{
enum E { }
void N(params object[] p) {}
delegate void D();
void M()
{
E e1;
E e2;
string s1 = null;
string s2 = null;
object o1 = null;
object o2 = null;
bool bln;
bool? nbln;
D d1 = null;
D d2 = null;
int i = 1;
E e = 0;
int? ni = 1;
E? ne = 0;
int i1 = 0;
char chr;
sbyte i08 = 1;
short i16 = 1;
int i32 = 1;
long i64 = 1;
byte u08 = 1;
ushort u16 = 1;
uint u32 = 1;
ulong u64 = 1;
float r32 = 1;
double r64 = 1;
decimal dec; // UNDONE: Decimal constants not supported yet.
char? nchr = null;
sbyte? ni08 = 1;
short? ni16 = 1;
int? ni32 = 1;
long? ni64 = 1;
byte? nu08 = 1;
ushort? nu16 = 1;
uint? nu32 = 1;
ulong? nu64 = 1;
float? nr32 = 1;
double? nr64 = 1;
decimal? ndec; // UNDONE: Decimal constants not supported yet.
N(
";
private const string Postfix = @"
);
}
}
";
private const string EnumAddition = Prefix + @"
i + e, //-UnderlyingAndEnumAddition
i + ne, //-LiftedUnderlyingAndEnumAddition
e + i, //-EnumAndUnderlyingAddition
e + ni, //-LiftedEnumAndUnderlyingAddition
ni + e, //-LiftedUnderlyingAndEnumAddition
ni + ne, //-LiftedUnderlyingAndEnumAddition
ne + i, //-LiftedEnumAndUnderlyingAddition
ne + ni //-LiftedEnumAndUnderlyingAddition" + Postfix;
private const string DelegateAddition = Prefix + @"
d1 + d2 //-DelegateCombination" + Postfix;
private const string StringAddition = Prefix + @"
s1 + s1, //-StringConcatenation
s1 + o1, //-StringAndObjectConcatenation
i1 + s1 //-ObjectAndStringConcatenation" + Postfix;
private const string ArithmeticTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR r32, //-FloatKIND
chr OPERATOR r64, //-DoubleKIND
chr OPERATOR dec, //-DecimalKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
chr OPERATOR nr32, //-LiftedFloatKIND
chr OPERATOR nr64, //-LiftedDoubleKIND
chr OPERATOR ndec, //-LiftedDecimalKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64, (ambiguous)
i16 OPERATOR r32, //-FloatKIND
i16 OPERATOR r64, //-DoubleKIND
i16 OPERATOR dec, //-DecimalKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
// i16 OPERATOR nu64, (ambiguous)
i16 OPERATOR nr32, //-LiftedFloatKIND
i16 OPERATOR nr64, //-LiftedDoubleKIND
i16 OPERATOR ndec, //-LiftedDecimalKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
// i32 OPERATOR u64, (ambiguous)
i32 OPERATOR r32, //-FloatKIND
i32 OPERATOR r64, //-DoubleKIND
i32 OPERATOR dec, //-DecimalKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
// i32 OPERATOR nu64, (ambiguous)
i32 OPERATOR nr32, //-LiftedFloatKIND
i32 OPERATOR nr64, //-LiftedDoubleKIND
i32 OPERATOR ndec, //-LiftedDecimalKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
// i64 OPERATOR u64, (ambiguous)
i64 OPERATOR r32, //-FloatKIND
i64 OPERATOR r64, //-DoubleKIND
i64 OPERATOR dec, //-DecimalKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
// i64 OPERATOR nu64, (ambiguous)
i64 OPERATOR nr32, //-LiftedFloatKIND
i64 OPERATOR nr64, //-LiftedDoubleKIND
i64 OPERATOR ndec, //-LiftedDecimalKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
u16 OPERATOR u64, //-ULongKIND
u16 OPERATOR r32, //-FloatKIND
u16 OPERATOR r64, //-DoubleKIND
u16 OPERATOR dec, //-DecimalKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
u16 OPERATOR nu64, //-LiftedULongKIND
u16 OPERATOR nr32, //-LiftedFloatKIND
u16 OPERATOR nr64, //-LiftedDoubleKIND
u16 OPERATOR ndec, //-LiftedDecimalKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR r32, //-FloatKIND
u32 OPERATOR r64, //-DoubleKIND
u32 OPERATOR dec, //-DecimalKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR nr32, //-LiftedFloatKIND
u32 OPERATOR nr64, //-LiftedDoubleKIND
u32 OPERATOR ndec, //-LiftedDecimalKIND
u64 OPERATOR chr, //-ULongKIND
// u64 OPERATOR i16, (ambiguous)
// u64 OPERATOR i32, (ambiguous)
// u64 OPERATOR i64, (ambiguous)
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR r32, //-FloatKIND
u64 OPERATOR r64, //-DoubleKIND
u64 OPERATOR dec, //-DecimalKIND
u64 OPERATOR nchr, //-LiftedULongKIND
// u64 OPERATOR ni16, (ambiguous)
// u64 OPERATOR ni32, (ambiguous)
// u64 OPERATOR ni64, (ambiguous)
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR nr32, //-LiftedFloatKIND
u64 OPERATOR nr64, //-LiftedDoubleKIND
u64 OPERATOR ndec, //-LiftedDecimalKIND
r32 OPERATOR chr, //-FloatKIND
r32 OPERATOR i16, //-FloatKIND
r32 OPERATOR i32, //-FloatKIND
r32 OPERATOR i64, //-FloatKIND
r32 OPERATOR u16, //-FloatKIND
r32 OPERATOR u32, //-FloatKIND
r32 OPERATOR u64, //-FloatKIND
r32 OPERATOR r32, //-FloatKIND
r32 OPERATOR r64, //-DoubleKIND
// r32 OPERATOR dec, (none applicable)
r32 OPERATOR nchr, //-LiftedFloatKIND
r32 OPERATOR ni16, //-LiftedFloatKIND
r32 OPERATOR ni32, //-LiftedFloatKIND
r32 OPERATOR ni64, //-LiftedFloatKIND
r32 OPERATOR nu16, //-LiftedFloatKIND
r32 OPERATOR nu32, //-LiftedFloatKIND
r32 OPERATOR nu64, //-LiftedFloatKIND
r32 OPERATOR nr32, //-LiftedFloatKIND
r32 OPERATOR nr64, //-LiftedDoubleKIND
// r32 OPERATOR ndec, (none applicable)
r64 OPERATOR chr, //-DoubleKIND
r64 OPERATOR i16, //-DoubleKIND
r64 OPERATOR i32, //-DoubleKIND
r64 OPERATOR i64, //-DoubleKIND
r64 OPERATOR u16, //-DoubleKIND
r64 OPERATOR u32, //-DoubleKIND
r64 OPERATOR u64, //-DoubleKIND
r64 OPERATOR r32, //-DoubleKIND
r64 OPERATOR r64, //-DoubleKIND
// r64 OPERATOR dec, (none applicable)
r64 OPERATOR nchr, //-LiftedDoubleKIND
r64 OPERATOR ni16, //-LiftedDoubleKIND
r64 OPERATOR ni32, //-LiftedDoubleKIND
r64 OPERATOR ni64, //-LiftedDoubleKIND
r64 OPERATOR nu16, //-LiftedDoubleKIND
r64 OPERATOR nu32, //-LiftedDoubleKIND
r64 OPERATOR nu64, //-LiftedDoubleKIND
r64 OPERATOR nr32, //-LiftedDoubleKIND
r64 OPERATOR nr64, //-LiftedDoubleKIND
// r64 OPERATOR ndec, (none applicable)
dec OPERATOR chr, //-DecimalKIND
dec OPERATOR i16, //-DecimalKIND
dec OPERATOR i32, //-DecimalKIND
dec OPERATOR i64, //-DecimalKIND
dec OPERATOR u16, //-DecimalKIND
dec OPERATOR u32, //-DecimalKIND
dec OPERATOR u64, //-DecimalKIND
// dec OPERATOR r32, (none applicable)
// dec OPERATOR r64, (none applicable)
dec OPERATOR dec, //-DecimalKIND
dec OPERATOR nchr, //-LiftedDecimalKIND
dec OPERATOR ni16, //-LiftedDecimalKIND
dec OPERATOR ni32, //-LiftedDecimalKIND
dec OPERATOR ni64, //-LiftedDecimalKIND
dec OPERATOR nu16, //-LiftedDecimalKIND
dec OPERATOR nu32, //-LiftedDecimalKIND
dec OPERATOR nu64, //-LiftedDecimalKIND
// dec OPERATOR nr32, (none applicable)
// dec OPERATOR nr64, (none applicable)
dec OPERATOR ndec, //-LiftedDecimalKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR r32, //-LiftedFloatKIND
nchr OPERATOR r64, //-LiftedDoubleKIND
nchr OPERATOR dec, //-LiftedDecimalKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR nr32, //-LiftedFloatKIND
nchr OPERATOR nr64, //-LiftedDoubleKIND
nchr OPERATOR ndec, //-LiftedDecimalKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
// ni16 OPERATOR u64, (ambiguous)
ni16 OPERATOR r32, //-LiftedFloatKIND
ni16 OPERATOR r64, //-LiftedDoubleKIND
ni16 OPERATOR dec, //-LiftedDecimalKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
// ni16 OPERATOR nu64, (ambiguous)
ni16 OPERATOR nr32, //-LiftedFloatKIND
ni16 OPERATOR nr64, //-LiftedDoubleKIND
ni16 OPERATOR ndec, //-LiftedDecimalKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
// ni32 OPERATOR u64, (ambiguous)
ni32 OPERATOR r32, //-LiftedFloatKIND
ni32 OPERATOR r64, //-LiftedDoubleKIND
ni32 OPERATOR dec, //-LiftedDecimalKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
// ni32 OPERATOR nu64, (ambiguous)
ni32 OPERATOR nr32, //-LiftedFloatKIND
ni32 OPERATOR nr64, //-LiftedDoubleKIND
ni32 OPERATOR ndec, //-LiftedDecimalKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
// ni64 OPERATOR u64, (ambiguous)
ni64 OPERATOR r32, //-LiftedFloatKIND
ni64 OPERATOR r64, //-LiftedDoubleKIND
ni64 OPERATOR dec, //-LiftedDecimalKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
// ni64 OPERATOR nu64, (ambiguous)
ni64 OPERATOR nr32, //-LiftedFloatKIND
ni64 OPERATOR nr64, //-LiftedDoubleKIND
ni64 OPERATOR ndec, //-LiftedDecimalKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
nu16 OPERATOR u64, //-LiftedULongKIND
nu16 OPERATOR r32, //-LiftedFloatKIND
nu16 OPERATOR r64, //-LiftedDoubleKIND
nu16 OPERATOR dec, //-LiftedDecimalKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
nu16 OPERATOR nu64, //-LiftedULongKIND
nu16 OPERATOR nr32, //-LiftedFloatKIND
nu16 OPERATOR nr64, //-LiftedDoubleKIND
nu16 OPERATOR ndec, //-LiftedDecimalKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR r32, //-LiftedFloatKIND
nu32 OPERATOR r64, //-LiftedDoubleKIND
nu32 OPERATOR dec, //-LiftedDecimalKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR nr32, //-LiftedFloatKIND
nu32 OPERATOR nr64, //-LiftedDoubleKIND
nu32 OPERATOR ndec, //-LiftedDecimalKIND
nu64 OPERATOR chr, //-LiftedULongKIND
// nu64 OPERATOR i16, (ambiguous)
// nu64 OPERATOR i32, (ambiguous)
// nu64 OPERATOR i64, (ambiguous)
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR r32, //-LiftedFloatKIND
nu64 OPERATOR r64, //-LiftedDoubleKIND
nu64 OPERATOR dec, //-LiftedDecimalKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
// nu64 OPERATOR ni16, (ambiguous)
// nu64 OPERATOR ni32, (ambiguous)
// nu64 OPERATOR ni64, (ambiguous)
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR nr32, //-LiftedFloatKIND
nu64 OPERATOR nr64, //-LiftedDoubleKIND
nu64 OPERATOR ndec, //-LiftedDecimalKIND
nr32 OPERATOR chr, //-LiftedFloatKIND
nr32 OPERATOR i16, //-LiftedFloatKIND
nr32 OPERATOR i32, //-LiftedFloatKIND
nr32 OPERATOR i64, //-LiftedFloatKIND
nr32 OPERATOR u16, //-LiftedFloatKIND
nr32 OPERATOR u32, //-LiftedFloatKIND
nr32 OPERATOR u64, //-LiftedFloatKIND
nr32 OPERATOR r32, //-LiftedFloatKIND
nr32 OPERATOR r64, //-LiftedDoubleKIND
// nr32 OPERATOR dec, (none applicable)
nr32 OPERATOR nchr, //-LiftedFloatKIND
nr32 OPERATOR ni16, //-LiftedFloatKIND
nr32 OPERATOR ni32, //-LiftedFloatKIND
nr32 OPERATOR ni64, //-LiftedFloatKIND
nr32 OPERATOR nu16, //-LiftedFloatKIND
nr32 OPERATOR nu32, //-LiftedFloatKIND
nr32 OPERATOR nu64, //-LiftedFloatKIND
nr32 OPERATOR nr32, //-LiftedFloatKIND
nr32 OPERATOR nr64, //-LiftedDoubleKIND
// nr32 OPERATOR ndec, (none applicable)
nr64 OPERATOR chr, //-LiftedDoubleKIND
nr64 OPERATOR i16, //-LiftedDoubleKIND
nr64 OPERATOR i32, //-LiftedDoubleKIND
nr64 OPERATOR i64, //-LiftedDoubleKIND
nr64 OPERATOR u16, //-LiftedDoubleKIND
nr64 OPERATOR u32, //-LiftedDoubleKIND
nr64 OPERATOR u64, //-LiftedDoubleKIND
nr64 OPERATOR r32, //-LiftedDoubleKIND
nr64 OPERATOR r64, //-LiftedDoubleKIND
// nr64 OPERATOR dec, (none applicable)
nr64 OPERATOR nchr, //-LiftedDoubleKIND
nr64 OPERATOR ni16, //-LiftedDoubleKIND
nr64 OPERATOR ni32, //-LiftedDoubleKIND
nr64 OPERATOR ni64, //-LiftedDoubleKIND
nr64 OPERATOR nu16, //-LiftedDoubleKIND
nr64 OPERATOR nu32, //-LiftedDoubleKIND
nr64 OPERATOR nu64, //-LiftedDoubleKIND
nr64 OPERATOR nr32, //-LiftedDoubleKIND
nr64 OPERATOR nr64, //-LiftedDoubleKIND
// nr64 OPERATOR ndec, (none applicable)
ndec OPERATOR chr, //-LiftedDecimalKIND
ndec OPERATOR i16, //-LiftedDecimalKIND
ndec OPERATOR i32, //-LiftedDecimalKIND
ndec OPERATOR i64, //-LiftedDecimalKIND
ndec OPERATOR u16, //-LiftedDecimalKIND
ndec OPERATOR u32, //-LiftedDecimalKIND
ndec OPERATOR u64, //-LiftedDecimalKIND
// ndec OPERATOR r32, (none applicable)
// ndec OPERATOR r64, (none applicable)
ndec OPERATOR dec, //-LiftedDecimalKIND
ndec OPERATOR nchr, //-LiftedDecimalKIND
ndec OPERATOR ni16, //-LiftedDecimalKIND
ndec OPERATOR ni32, //-LiftedDecimalKIND
ndec OPERATOR ni64, //-LiftedDecimalKIND
ndec OPERATOR nu16, //-LiftedDecimalKIND
ndec OPERATOR nu32, //-LiftedDecimalKIND
ndec OPERATOR nu64, //-LiftedDecimalKIND
// ndec OPERATOR nr32, (none applicable)
// ndec OPERATOR nr64, (none applicable)
ndec OPERATOR ndec //-LiftedDecimalKIND" + Postfix;
private const string EnumSubtraction = Prefix + @"
e - e, //-EnumSubtraction
e - ne, //-LiftedEnumSubtraction
e - i, //-EnumAndUnderlyingSubtraction
e - ni, //-LiftedEnumAndUnderlyingSubtraction
ne - e, //-LiftedEnumSubtraction
ne - ne, //-LiftedEnumSubtraction
ne - i, //-LiftedEnumAndUnderlyingSubtraction
ne - ni //-LiftedEnumAndUnderlyingSubtraction" + Postfix;
private const string DelegateSubtraction = Prefix + "d1 - d2 //-DelegateRemoval" + Postfix;
private const string ShiftTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-UIntKIND
u32 OPERATOR i32, //-UIntKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedUIntKIND
u32 OPERATOR ni32, //-LiftedUIntKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u64 OPERATOR chr, //-ULongKIND
u64 OPERATOR i16, //-ULongKIND
u64 OPERATOR i32, //-ULongKIND
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR nchr, //-LiftedULongKIND
u64 OPERATOR ni16, //-LiftedULongKIND
u64 OPERATOR ni32, //-LiftedULongKIND
u64 OPERATOR nu16, //-LiftedULongKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedUIntKIND
nu32 OPERATOR i32, //-LiftedUIntKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedUIntKIND
nu32 OPERATOR ni32, //-LiftedUIntKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu64 OPERATOR chr, //-LiftedULongKIND
nu64 OPERATOR i16, //-LiftedULongKIND
nu64 OPERATOR i32, //-LiftedULongKIND
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
nu64 OPERATOR ni16, //-LiftedULongKIND
nu64 OPERATOR ni32, //-LiftedULongKIND
nu64 OPERATOR nu16 //-LiftedULongKIND
" + Postfix;
private const string LogicTemplate = Prefix + @"
bln OPERATOR bln, //-BoolKIND
bln OPERATOR nbln, //-LiftedBoolKIND
nbln OPERATOR bln, //-LiftedBoolKIND
nbln OPERATOR nbln, //-LiftedBoolKIND
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64,
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
//i16 OPERATOR nu64,
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
//i32 OPERATOR u64,
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
//i32 OPERATOR nu64,
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
//i64 OPERATOR u64,
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
//i64 OPERATOR nu64,
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
u16 OPERATOR u64, //-ULongKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
u16 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR chr, //-ULongKIND
//u64 OPERATOR i16,
//u64 OPERATOR i32,
//u64 OPERATOR i64,
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR nchr, //-LiftedULongKIND
//u64 OPERATOR ni16,
//u64 OPERATOR ni32,
//u64 OPERATOR ni64,
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
//ni16 OPERATOR u64,
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
//ni16 OPERATOR nu64,
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
//ni32 OPERATOR u64,
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
//ni32 OPERATOR nu64,
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
//ni64 OPERATOR u64,
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
//ni64 OPERATOR nu64,
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
nu16 OPERATOR u64, //-LiftedULongKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
nu16 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR chr, //-LiftedULongKIND
//nu64 OPERATOR i16,
//nu64 OPERATOR i32,
//nu64 OPERATOR i64,
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
//nu64 OPERATOR ni16,
//nu64 OPERATOR ni32,
//nu64 OPERATOR ni64,
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64 //-LiftedULongKIND
" + Postfix;
//built-in operator only works for bools (not even lifted bools)
private const string ShortCircuitTemplate = Prefix + @"
bln OPERATOR bln, //-LogicalBoolKIND
" + Postfix;
private const string EnumLogicTemplate = Prefix + @"
e OPERATOR e, //-EnumKIND
e OPERATOR ne, //-LiftedEnumKIND
ne OPERATOR e, //-LiftedEnumKIND
ne OPERATOR ne //-LiftedEnumKIND" + Postfix;
private const string ComparisonTemplate = Prefix + @"
chr OPERATOR chr, //-IntKIND
chr OPERATOR i16, //-IntKIND
chr OPERATOR i32, //-IntKIND
chr OPERATOR i64, //-LongKIND
chr OPERATOR u16, //-IntKIND
chr OPERATOR u32, //-UIntKIND
chr OPERATOR u64, //-ULongKIND
chr OPERATOR r32, //-FloatKIND
chr OPERATOR r64, //-DoubleKIND
chr OPERATOR dec, //-DecimalKIND
chr OPERATOR nchr, //-LiftedIntKIND
chr OPERATOR ni16, //-LiftedIntKIND
chr OPERATOR ni32, //-LiftedIntKIND
chr OPERATOR ni64, //-LiftedLongKIND
chr OPERATOR nu16, //-LiftedIntKIND
chr OPERATOR nu32, //-LiftedUIntKIND
chr OPERATOR nu64, //-LiftedULongKIND
chr OPERATOR nr32, //-LiftedFloatKIND
chr OPERATOR nr64, //-LiftedDoubleKIND
chr OPERATOR ndec, //-LiftedDecimalKIND
i16 OPERATOR chr, //-IntKIND
i16 OPERATOR i16, //-IntKIND
i16 OPERATOR i32, //-IntKIND
i16 OPERATOR i64, //-LongKIND
i16 OPERATOR u16, //-IntKIND
i16 OPERATOR u32, //-LongKIND
// i16 OPERATOR u64, (ambiguous)
i16 OPERATOR r32, //-FloatKIND
i16 OPERATOR r64, //-DoubleKIND
i16 OPERATOR dec, //-DecimalKIND
i16 OPERATOR nchr, //-LiftedIntKIND
i16 OPERATOR ni16, //-LiftedIntKIND
i16 OPERATOR ni32, //-LiftedIntKIND
i16 OPERATOR ni64, //-LiftedLongKIND
i16 OPERATOR nu16, //-LiftedIntKIND
i16 OPERATOR nu32, //-LiftedLongKIND
// i16 OPERATOR nu64, (ambiguous)
i16 OPERATOR nr32, //-LiftedFloatKIND
i16 OPERATOR nr64, //-LiftedDoubleKIND
i16 OPERATOR ndec, //-LiftedDecimalKIND
i32 OPERATOR chr, //-IntKIND
i32 OPERATOR i16, //-IntKIND
i32 OPERATOR i32, //-IntKIND
i32 OPERATOR i64, //-LongKIND
i32 OPERATOR u16, //-IntKIND
i32 OPERATOR u32, //-LongKIND
// i32 OPERATOR u64, (ambiguous)
i32 OPERATOR r32, //-FloatKIND
i32 OPERATOR r64, //-DoubleKIND
i32 OPERATOR dec, //-DecimalKIND
i32 OPERATOR nchr, //-LiftedIntKIND
i32 OPERATOR ni16, //-LiftedIntKIND
i32 OPERATOR ni32, //-LiftedIntKIND
i32 OPERATOR ni64, //-LiftedLongKIND
i32 OPERATOR nu16, //-LiftedIntKIND
i32 OPERATOR nu32, //-LiftedLongKIND
// i32 OPERATOR nu64, (ambiguous)
i32 OPERATOR nr32, //-LiftedFloatKIND
i32 OPERATOR nr64, //-LiftedDoubleKIND
i32 OPERATOR ndec, //-LiftedDecimalKIND
i64 OPERATOR chr, //-LongKIND
i64 OPERATOR i16, //-LongKIND
i64 OPERATOR i32, //-LongKIND
i64 OPERATOR i64, //-LongKIND
i64 OPERATOR u16, //-LongKIND
i64 OPERATOR u32, //-LongKIND
// i64 OPERATOR u64, (ambiguous)
i64 OPERATOR r32, //-FloatKIND
i64 OPERATOR r64, //-DoubleKIND
i64 OPERATOR dec, //-DecimalKIND
i64 OPERATOR nchr, //-LiftedLongKIND
i64 OPERATOR ni16, //-LiftedLongKIND
i64 OPERATOR ni32, //-LiftedLongKIND
i64 OPERATOR ni64, //-LiftedLongKIND
i64 OPERATOR nu16, //-LiftedLongKIND
i64 OPERATOR nu32, //-LiftedLongKIND
// i64 OPERATOR nu64, (ambiguous)
i64 OPERATOR nr32, //-LiftedFloatKIND
i64 OPERATOR nr64, //-LiftedDoubleKIND
i64 OPERATOR ndec, //-LiftedDecimalKIND
u16 OPERATOR chr, //-IntKIND
u16 OPERATOR i16, //-IntKIND
u16 OPERATOR i32, //-IntKIND
u16 OPERATOR i64, //-LongKIND
u16 OPERATOR u16, //-IntKIND
u16 OPERATOR u32, //-UIntKIND
//u16 OPERATOR u64, (ambiguous)
u16 OPERATOR r32, //-FloatKIND
u16 OPERATOR r64, //-DoubleKIND
u16 OPERATOR dec, //-DecimalKIND
u16 OPERATOR nchr, //-LiftedIntKIND
u16 OPERATOR ni16, //-LiftedIntKIND
u16 OPERATOR ni32, //-LiftedIntKIND
u16 OPERATOR ni64, //-LiftedLongKIND
u16 OPERATOR nu16, //-LiftedIntKIND
u16 OPERATOR nu32, //-LiftedUIntKIND
//u16 OPERATOR nu64, (ambiguous)
u16 OPERATOR nr32, //-LiftedFloatKIND
u16 OPERATOR nr64, //-LiftedDoubleKIND
u16 OPERATOR ndec, //-LiftedDecimalKIND
u32 OPERATOR chr, //-UIntKIND
u32 OPERATOR i16, //-LongKIND
u32 OPERATOR i32, //-LongKIND
u32 OPERATOR i64, //-LongKIND
u32 OPERATOR u16, //-UIntKIND
u32 OPERATOR u32, //-UIntKIND
u32 OPERATOR u64, //-ULongKIND
u32 OPERATOR r32, //-FloatKIND
u32 OPERATOR r64, //-DoubleKIND
u32 OPERATOR dec, //-DecimalKIND
u32 OPERATOR nchr, //-LiftedUIntKIND
u32 OPERATOR ni16, //-LiftedLongKIND
u32 OPERATOR ni32, //-LiftedLongKIND
u32 OPERATOR ni64, //-LiftedLongKIND
u32 OPERATOR nu16, //-LiftedUIntKIND
u32 OPERATOR nu32, //-LiftedUIntKIND
u32 OPERATOR nu64, //-LiftedULongKIND
u32 OPERATOR nr32, //-LiftedFloatKIND
u32 OPERATOR nr64, //-LiftedDoubleKIND
u32 OPERATOR ndec, //-LiftedDecimalKIND
u64 OPERATOR chr, //-ULongKIND
// u64 OPERATOR i16, (ambiguous)
// u64 OPERATOR i32, (ambiguous)
// u64 OPERATOR i64, (ambiguous)
u64 OPERATOR u16, //-ULongKIND
u64 OPERATOR u32, //-ULongKIND
u64 OPERATOR u64, //-ULongKIND
u64 OPERATOR r32, //-FloatKIND
u64 OPERATOR r64, //-DoubleKIND
u64 OPERATOR dec, //-DecimalKIND
u64 OPERATOR nchr, //-LiftedULongKIND
// u64 OPERATOR ni16, (ambiguous)
// u64 OPERATOR ni32, (ambiguous)
// u64 OPERATOR ni64, (ambiguous)
u64 OPERATOR nu16, //-LiftedULongKIND
u64 OPERATOR nu32, //-LiftedULongKIND
u64 OPERATOR nu64, //-LiftedULongKIND
u64 OPERATOR nr32, //-LiftedFloatKIND
u64 OPERATOR nr64, //-LiftedDoubleKIND
u64 OPERATOR ndec, //-LiftedDecimalKIND
r32 OPERATOR chr, //-FloatKIND
r32 OPERATOR i16, //-FloatKIND
r32 OPERATOR i32, //-FloatKIND
r32 OPERATOR i64, //-FloatKIND
r32 OPERATOR u16, //-FloatKIND
r32 OPERATOR u32, //-FloatKIND
r32 OPERATOR u64, //-FloatKIND
r32 OPERATOR r32, //-FloatKIND
r32 OPERATOR r64, //-DoubleKIND
// r32 OPERATOR dec, (none applicable)
r32 OPERATOR nchr, //-LiftedFloatKIND
r32 OPERATOR ni16, //-LiftedFloatKIND
r32 OPERATOR ni32, //-LiftedFloatKIND
r32 OPERATOR ni64, //-LiftedFloatKIND
r32 OPERATOR nu16, //-LiftedFloatKIND
r32 OPERATOR nu32, //-LiftedFloatKIND
r32 OPERATOR nu64, //-LiftedFloatKIND
r32 OPERATOR nr32, //-LiftedFloatKIND
r32 OPERATOR nr64, //-LiftedDoubleKIND
// r32 OPERATOR ndec, (none applicable)
r64 OPERATOR chr, //-DoubleKIND
r64 OPERATOR i16, //-DoubleKIND
r64 OPERATOR i32, //-DoubleKIND
r64 OPERATOR i64, //-DoubleKIND
r64 OPERATOR u16, //-DoubleKIND
r64 OPERATOR u32, //-DoubleKIND
r64 OPERATOR u64, //-DoubleKIND
r64 OPERATOR r32, //-DoubleKIND
r64 OPERATOR r64, //-DoubleKIND
// r64 OPERATOR dec, (none applicable)
r64 OPERATOR nchr, //-LiftedDoubleKIND
r64 OPERATOR ni16, //-LiftedDoubleKIND
r64 OPERATOR ni32, //-LiftedDoubleKIND
r64 OPERATOR ni64, //-LiftedDoubleKIND
r64 OPERATOR nu16, //-LiftedDoubleKIND
r64 OPERATOR nu32, //-LiftedDoubleKIND
r64 OPERATOR nu64, //-LiftedDoubleKIND
r64 OPERATOR nr32, //-LiftedDoubleKIND
r64 OPERATOR nr64, //-LiftedDoubleKIND
// r64 OPERATOR ndec, (none applicable)
dec OPERATOR chr, //-DecimalKIND
dec OPERATOR i16, //-DecimalKIND
dec OPERATOR i32, //-DecimalKIND
dec OPERATOR i64, //-DecimalKIND
dec OPERATOR u16, //-DecimalKIND
dec OPERATOR u32, //-DecimalKIND
dec OPERATOR u64, //-DecimalKIND
// dec OPERATOR r32, (none applicable)
// dec OPERATOR r64, (none applicable)
dec OPERATOR dec, //-DecimalKIND
dec OPERATOR nchr, //-LiftedDecimalKIND
dec OPERATOR ni16, //-LiftedDecimalKIND
dec OPERATOR ni32, //-LiftedDecimalKIND
dec OPERATOR ni64, //-LiftedDecimalKIND
dec OPERATOR nu16, //-LiftedDecimalKIND
dec OPERATOR nu32, //-LiftedDecimalKIND
dec OPERATOR nu64, //-LiftedDecimalKIND
// dec OPERATOR nr32, (none applicable)
// dec OPERATOR nr64, (none applicable)
dec OPERATOR ndec, //-LiftedDecimalKIND
nchr OPERATOR chr, //-LiftedIntKIND
nchr OPERATOR i16, //-LiftedIntKIND
nchr OPERATOR i32, //-LiftedIntKIND
nchr OPERATOR i64, //-LiftedLongKIND
nchr OPERATOR u16, //-LiftedIntKIND
nchr OPERATOR u32, //-LiftedUIntKIND
nchr OPERATOR u64, //-LiftedULongKIND
nchr OPERATOR r32, //-LiftedFloatKIND
nchr OPERATOR r64, //-LiftedDoubleKIND
nchr OPERATOR dec, //-LiftedDecimalKIND
nchr OPERATOR nchr, //-LiftedIntKIND
nchr OPERATOR ni16, //-LiftedIntKIND
nchr OPERATOR ni32, //-LiftedIntKIND
nchr OPERATOR ni64, //-LiftedLongKIND
nchr OPERATOR nu16, //-LiftedIntKIND
nchr OPERATOR nu32, //-LiftedUIntKIND
nchr OPERATOR nu64, //-LiftedULongKIND
nchr OPERATOR nr32, //-LiftedFloatKIND
nchr OPERATOR nr64, //-LiftedDoubleKIND
nchr OPERATOR ndec, //-LiftedDecimalKIND
ni16 OPERATOR chr, //-LiftedIntKIND
ni16 OPERATOR i16, //-LiftedIntKIND
ni16 OPERATOR i32, //-LiftedIntKIND
ni16 OPERATOR i64, //-LiftedLongKIND
ni16 OPERATOR u16, //-LiftedIntKIND
ni16 OPERATOR u32, //-LiftedLongKIND
// ni16 OPERATOR u64, (ambiguous)
ni16 OPERATOR r32, //-LiftedFloatKIND
ni16 OPERATOR r64, //-LiftedDoubleKIND
ni16 OPERATOR dec, //-LiftedDecimalKIND
ni16 OPERATOR nchr, //-LiftedIntKIND
ni16 OPERATOR ni16, //-LiftedIntKIND
ni16 OPERATOR ni32, //-LiftedIntKIND
ni16 OPERATOR ni64, //-LiftedLongKIND
ni16 OPERATOR nu16, //-LiftedIntKIND
ni16 OPERATOR nu32, //-LiftedLongKIND
// ni16 OPERATOR nu64, (ambiguous)
ni16 OPERATOR nr32, //-LiftedFloatKIND
ni16 OPERATOR nr64, //-LiftedDoubleKIND
ni16 OPERATOR ndec, //-LiftedDecimalKIND
ni32 OPERATOR chr, //-LiftedIntKIND
ni32 OPERATOR i16, //-LiftedIntKIND
ni32 OPERATOR i32, //-LiftedIntKIND
ni32 OPERATOR i64, //-LiftedLongKIND
ni32 OPERATOR u16, //-LiftedIntKIND
ni32 OPERATOR u32, //-LiftedLongKIND
// ni32 OPERATOR u64, (ambiguous)
ni32 OPERATOR r32, //-LiftedFloatKIND
ni32 OPERATOR r64, //-LiftedDoubleKIND
ni32 OPERATOR dec, //-LiftedDecimalKIND
ni32 OPERATOR nchr, //-LiftedIntKIND
ni32 OPERATOR ni16, //-LiftedIntKIND
ni32 OPERATOR ni32, //-LiftedIntKIND
ni32 OPERATOR ni64, //-LiftedLongKIND
ni32 OPERATOR nu16, //-LiftedIntKIND
ni32 OPERATOR nu32, //-LiftedLongKIND
// ni32 OPERATOR nu64, (ambiguous)
ni32 OPERATOR nr32, //-LiftedFloatKIND
ni32 OPERATOR nr64, //-LiftedDoubleKIND
ni32 OPERATOR ndec, //-LiftedDecimalKIND
ni64 OPERATOR chr, //-LiftedLongKIND
ni64 OPERATOR i16, //-LiftedLongKIND
ni64 OPERATOR i32, //-LiftedLongKIND
ni64 OPERATOR i64, //-LiftedLongKIND
ni64 OPERATOR u16, //-LiftedLongKIND
ni64 OPERATOR u32, //-LiftedLongKIND
// ni64 OPERATOR u64, (ambiguous)
ni64 OPERATOR r32, //-LiftedFloatKIND
ni64 OPERATOR r64, //-LiftedDoubleKIND
ni64 OPERATOR dec, //-LiftedDecimalKIND
ni64 OPERATOR nchr, //-LiftedLongKIND
ni64 OPERATOR ni16, //-LiftedLongKIND
ni64 OPERATOR ni32, //-LiftedLongKIND
ni64 OPERATOR ni64, //-LiftedLongKIND
ni64 OPERATOR nu16, //-LiftedLongKIND
ni64 OPERATOR nu32, //-LiftedLongKIND
// ni64 OPERATOR nu64, (ambiguous)
ni64 OPERATOR nr32, //-LiftedFloatKIND
ni64 OPERATOR nr64, //-LiftedDoubleKIND
ni64 OPERATOR ndec, //-LiftedDecimalKIND
nu16 OPERATOR chr, //-LiftedIntKIND
nu16 OPERATOR i16, //-LiftedIntKIND
nu16 OPERATOR i32, //-LiftedIntKIND
nu16 OPERATOR i64, //-LiftedLongKIND
nu16 OPERATOR u16, //-LiftedIntKIND
nu16 OPERATOR u32, //-LiftedUIntKIND
//nu16 OPERATOR u64, (ambiguous)
nu16 OPERATOR r32, //-LiftedFloatKIND
nu16 OPERATOR r64, //-LiftedDoubleKIND
nu16 OPERATOR dec, //-LiftedDecimalKIND
nu16 OPERATOR nchr, //-LiftedIntKIND
nu16 OPERATOR ni16, //-LiftedIntKIND
nu16 OPERATOR ni32, //-LiftedIntKIND
nu16 OPERATOR ni64, //-LiftedLongKIND
nu16 OPERATOR nu16, //-LiftedIntKIND
nu16 OPERATOR nu32, //-LiftedUIntKIND
//nu16 OPERATOR nu64, (ambiguous)
nu16 OPERATOR nr32, //-LiftedFloatKIND
nu16 OPERATOR nr64, //-LiftedDoubleKIND
nu16 OPERATOR ndec, //-LiftedDecimalKIND
nu32 OPERATOR chr, //-LiftedUIntKIND
nu32 OPERATOR i16, //-LiftedLongKIND
nu32 OPERATOR i32, //-LiftedLongKIND
nu32 OPERATOR i64, //-LiftedLongKIND
nu32 OPERATOR u16, //-LiftedUIntKIND
nu32 OPERATOR u32, //-LiftedUIntKIND
nu32 OPERATOR u64, //-LiftedULongKIND
nu32 OPERATOR r32, //-LiftedFloatKIND
nu32 OPERATOR r64, //-LiftedDoubleKIND
nu32 OPERATOR dec, //-LiftedDecimalKIND
nu32 OPERATOR nchr, //-LiftedUIntKIND
nu32 OPERATOR ni16, //-LiftedLongKIND
nu32 OPERATOR ni32, //-LiftedLongKIND
nu32 OPERATOR ni64, //-LiftedLongKIND
nu32 OPERATOR nu16, //-LiftedUIntKIND
nu32 OPERATOR nu32, //-LiftedUIntKIND
nu32 OPERATOR nu64, //-LiftedULongKIND
nu32 OPERATOR nr32, //-LiftedFloatKIND
nu32 OPERATOR nr64, //-LiftedDoubleKIND
nu32 OPERATOR ndec, //-LiftedDecimalKIND
nu64 OPERATOR chr, //-LiftedULongKIND
// nu64 OPERATOR i16, (ambiguous)
// nu64 OPERATOR i32, (ambiguous)
// nu64 OPERATOR i64, (ambiguous)
nu64 OPERATOR u16, //-LiftedULongKIND
nu64 OPERATOR u32, //-LiftedULongKIND
nu64 OPERATOR u64, //-LiftedULongKIND
nu64 OPERATOR r32, //-LiftedFloatKIND
nu64 OPERATOR r64, //-LiftedDoubleKIND
nu64 OPERATOR dec, //-LiftedDecimalKIND
nu64 OPERATOR nchr, //-LiftedULongKIND
// nu64 OPERATOR ni16, (ambiguous)
// nu64 OPERATOR ni32, (ambiguous)
// nu64 OPERATOR ni64, (ambiguous)
nu64 OPERATOR nu16, //-LiftedULongKIND
nu64 OPERATOR nu32, //-LiftedULongKIND
nu64 OPERATOR nu64, //-LiftedULongKIND
nu64 OPERATOR nr32, //-LiftedFloatKIND
nu64 OPERATOR nr64, //-LiftedDoubleKIND
nu64 OPERATOR ndec, //-LiftedDecimalKIND
nr32 OPERATOR chr, //-LiftedFloatKIND
nr32 OPERATOR i16, //-LiftedFloatKIND
nr32 OPERATOR i32, //-LiftedFloatKIND
nr32 OPERATOR i64, //-LiftedFloatKIND
nr32 OPERATOR u16, //-LiftedFloatKIND
nr32 OPERATOR u32, //-LiftedFloatKIND
nr32 OPERATOR u64, //-LiftedFloatKIND
nr32 OPERATOR r32, //-LiftedFloatKIND
nr32 OPERATOR r64, //-LiftedDoubleKIND
// nr32 OPERATOR dec, (none applicable)
nr32 OPERATOR nchr, //-LiftedFloatKIND
nr32 OPERATOR ni16, //-LiftedFloatKIND
nr32 OPERATOR ni32, //-LiftedFloatKIND
nr32 OPERATOR ni64, //-LiftedFloatKIND
nr32 OPERATOR nu16, //-LiftedFloatKIND
nr32 OPERATOR nu32, //-LiftedFloatKIND
nr32 OPERATOR nu64, //-LiftedFloatKIND
nr32 OPERATOR nr32, //-LiftedFloatKIND
nr32 OPERATOR nr64, //-LiftedDoubleKIND
// nr32 OPERATOR ndec, (none applicable)
nr64 OPERATOR chr, //-LiftedDoubleKIND
nr64 OPERATOR i16, //-LiftedDoubleKIND
nr64 OPERATOR i32, //-LiftedDoubleKIND
nr64 OPERATOR i64, //-LiftedDoubleKIND
nr64 OPERATOR u16, //-LiftedDoubleKIND
nr64 OPERATOR u32, //-LiftedDoubleKIND
nr64 OPERATOR u64, //-LiftedDoubleKIND
nr64 OPERATOR r32, //-LiftedDoubleKIND
nr64 OPERATOR r64, //-LiftedDoubleKIND
// nr64 OPERATOR dec, (none applicable)
nr64 OPERATOR nchr, //-LiftedDoubleKIND
nr64 OPERATOR ni16, //-LiftedDoubleKIND
nr64 OPERATOR ni32, //-LiftedDoubleKIND
nr64 OPERATOR ni64, //-LiftedDoubleKIND
nr64 OPERATOR nu16, //-LiftedDoubleKIND
nr64 OPERATOR nu32, //-LiftedDoubleKIND
nr64 OPERATOR nu64, //-LiftedDoubleKIND
nr64 OPERATOR nr32, //-LiftedDoubleKIND
nr64 OPERATOR nr64, //-LiftedDoubleKIND
// nr64 OPERATOR ndec, (none applicable)
ndec OPERATOR chr, //-LiftedDecimalKIND
ndec OPERATOR i16, //-LiftedDecimalKIND
ndec OPERATOR i32, //-LiftedDecimalKIND
ndec OPERATOR i64, //-LiftedDecimalKIND
ndec OPERATOR u16, //-LiftedDecimalKIND
ndec OPERATOR u32, //-LiftedDecimalKIND
ndec OPERATOR u64, //-LiftedDecimalKIND
// ndec OPERATOR r32, (none applicable)
// ndec OPERATOR r64, (none applicable)
ndec OPERATOR dec, //-LiftedDecimalKIND
ndec OPERATOR nchr, //-LiftedDecimalKIND
ndec OPERATOR ni16, //-LiftedDecimalKIND
ndec OPERATOR ni32, //-LiftedDecimalKIND
ndec OPERATOR ni64, //-LiftedDecimalKIND
ndec OPERATOR nu16, //-LiftedDecimalKIND
ndec OPERATOR nu32, //-LiftedDecimalKIND
ndec OPERATOR nu64, //-LiftedDecimalKIND
// ndec OPERATOR nr32, (none applicable)
// ndec OPERATOR nr64, (none applicable)
ndec OPERATOR ndec //-LiftedDecimalKIND
" + Postfix;
private const string EqualityTemplate = Prefix + @"
e1 OPERATOR e2, //-EnumKIND
e1 OPERATOR o2, //-KIND
d1 OPERATOR d2, //-DelegateKIND
d1 OPERATOR o2, //-ObjectKIND
s1 OPERATOR s2, //-StringKIND
s1 OPERATOR o2, //-ObjectKIND
o1 OPERATOR e2, //-KIND
o1 OPERATOR d2, //-ObjectKIND
o1 OPERATOR s2, //-ObjectKIND
o1 OPERATOR o2 //-ObjectKIND" + Postfix;
private const string PostfixIncrementTemplate = Prefix + @"
e OPERATOR, //-EnumKIND
chr OPERATOR, //-CharKIND
i08 OPERATOR, //-SByteKIND
i16 OPERATOR, //-ShortKIND
i32 OPERATOR, //-IntKIND
i64 OPERATOR, //-LongKIND
u08 OPERATOR, //-ByteKIND
u16 OPERATOR, //-UShortKIND
u32 OPERATOR, //-UIntKIND
u64 OPERATOR, //-ULongKIND
r32 OPERATOR, //-FloatKIND
r64 OPERATOR, //-DoubleKIND
dec OPERATOR, //-DecimalKIND
ne OPERATOR, //-LiftedEnumKIND
nchr OPERATOR, //-LiftedCharKIND
ni08 OPERATOR, //-LiftedSByteKIND
ni16 OPERATOR, //-LiftedShortKIND
ni32 OPERATOR, //-LiftedIntKIND
ni64 OPERATOR, //-LiftedLongKIND
nu08 OPERATOR, //-LiftedByteKIND
nu16 OPERATOR, //-LiftedUShortKIND
nu32 OPERATOR, //-LiftedUIntKIND
nu64 OPERATOR, //-LiftedULongKIND
nr32 OPERATOR, //-LiftedFloatKIND
nr64 OPERATOR, //-LiftedDoubleKIND
ndec OPERATOR //-LiftedDecimalKIND
" + Postfix;
private const string PrefixIncrementTemplate = Prefix + @"
OPERATOR e , //-EnumKIND
OPERATOR chr , //-CharKIND
OPERATOR i08 , //-SByteKIND
OPERATOR i16 , //-ShortKIND
OPERATOR i32 , //-IntKIND
OPERATOR i64 , //-LongKIND
OPERATOR u08 , //-ByteKIND
OPERATOR u16 , //-UShortKIND
OPERATOR u32 , //-UIntKIND
OPERATOR u64 , //-ULongKIND
OPERATOR r32 , //-FloatKIND
OPERATOR r64 , //-DoubleKIND
OPERATOR dec , //-DecimalKIND
OPERATOR ne , //-LiftedEnumKIND
OPERATOR nchr , //-LiftedCharKIND
OPERATOR ni08 , //-LiftedSByteKIND
OPERATOR ni16 , //-LiftedShortKIND
OPERATOR ni32 , //-LiftedIntKIND
OPERATOR ni64 , //-LiftedLongKIND
OPERATOR nu08 , //-LiftedByteKIND
OPERATOR nu16 , //-LiftedUShortKIND
OPERATOR nu32 , //-LiftedUIntKIND
OPERATOR nu64 , //-LiftedULongKIND
OPERATOR nr32 , //-LiftedFloatKIND
OPERATOR nr64 , //-LiftedDoubleKIND
OPERATOR ndec //-LiftedDecimalKIND" + Postfix;
private const string UnaryPlus = Prefix + @"
+ chr, //-IntUnaryPlus
+ i08, //-IntUnaryPlus
+ i16, //-IntUnaryPlus
+ i32, //-IntUnaryPlus
+ i64, //-LongUnaryPlus
+ u08, //-IntUnaryPlus
+ u16, //-IntUnaryPlus
+ u32, //-UIntUnaryPlus
+ u64, //-ULongUnaryPlus
+ r32, //-FloatUnaryPlus
+ r64, //-DoubleUnaryPlus
+ dec, //-DecimalUnaryPlus
+ nchr, //-LiftedIntUnaryPlus
+ ni08, //-LiftedIntUnaryPlus
+ ni16, //-LiftedIntUnaryPlus
+ ni32, //-LiftedIntUnaryPlus
+ ni64, //-LiftedLongUnaryPlus
+ nu08, //-LiftedIntUnaryPlus
+ nu16, //-LiftedIntUnaryPlus
+ nu32, //-LiftedUIntUnaryPlus
+ nu64, //-LiftedULongUnaryPlus
+ nr32, //-LiftedFloatUnaryPlus
+ nr64, //-LiftedDoubleUnaryPlus
+ ndec //-LiftedDecimalUnaryPlus" + Postfix;
private const string UnaryMinus = Prefix + @"
- chr, //-IntUnaryMinus
- i08, //-IntUnaryMinus
- i16, //-IntUnaryMinus
- i32, //-IntUnaryMinus
- i64, //-LongUnaryMinus
- u08, //-IntUnaryMinus
- u16, //-IntUnaryMinus
- u32, //-LongUnaryMinus
- r32, //-FloatUnaryMinus
- r64, //-DoubleUnaryMinus
- dec, //-DecimalUnaryMinus
- nchr, //-LiftedIntUnaryMinus
- ni08, //-LiftedIntUnaryMinus
- ni16, //-LiftedIntUnaryMinus
- ni32, //-LiftedIntUnaryMinus
- ni64, //-LiftedLongUnaryMinus
- nu08, //-LiftedIntUnaryMinus
- nu16, //-LiftedIntUnaryMinus
- nu32, //-LiftedLongUnaryMinus
- nr32, //-LiftedFloatUnaryMinus
- nr64, //-LiftedDoubleUnaryMinus
- ndec //-LiftedDecimalUnaryMinus" + Postfix;
private const string LogicalNegation = Prefix + @"
! bln, //-BoolLogicalNegation
! nbln //-LiftedBoolLogicalNegation" + Postfix;
private const string BitwiseComplement = Prefix + @"
~ e, //-EnumBitwiseComplement
~ chr, //-IntBitwiseComplement
~ i08, //-IntBitwiseComplement
~ i16, //-IntBitwiseComplement
~ i32, //-IntBitwiseComplement
~ i64, //-LongBitwiseComplement
~ u08, //-IntBitwiseComplement
~ u16, //-IntBitwiseComplement
~ u32, //-UIntBitwiseComplement
~ u64, //-ULongBitwiseComplement
~ ne, //-LiftedEnumBitwiseComplement
~ nchr, //-LiftedIntBitwiseComplement
~ ni08, //-LiftedIntBitwiseComplement
~ ni16, //-LiftedIntBitwiseComplement
~ ni32, //-LiftedIntBitwiseComplement
~ ni64, //-LiftedLongBitwiseComplement
~ nu08, //-LiftedIntBitwiseComplement
~ nu16, //-LiftedIntBitwiseComplement
~ nu32, //-LiftedUIntBitwiseComplement
~ nu64 //-LiftedULongBitwiseComplement
);
}
}" + Postfix;
#endregion
[Fact, WorkItem(527598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527598")]
public void UserDefinedOperatorOnPointerType()
{
CreateCompilation(@"
unsafe struct A
{
public static implicit operator int*(A x) { return null; }
static void M()
{
var x = new A();
int* y = null;
var z = x - y; // Dev11 generates CS0019...should compile
}
}
", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
// add better verification once this is implemented
}
[Fact]
public void TestNullCoalesce_Dynamic()
{
var source = @"
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
Dynamic_b_constant_null_a();
Dynamic_b_constant_null_a_nullable();
Dynamic_b_constant_not_null_a_nullable();
Dynamic_b_not_null_a();
Dynamic_b_not_null_a_nullable(10);
return 0;
}
public static D Dynamic_b_constant_null_a()
{
dynamic b = new D();
D a = null;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_constant_null_a_nullable()
{
dynamic b = new D();
int? a = null;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_constant_not_null_a_nullable()
{
dynamic b = new D();
int? a = 10;
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_not_null_a()
{
dynamic b = new D();
D a = new E();
dynamic z = a ?? b;
return z;
}
public static D Dynamic_b_not_null_a_nullable(int? c)
{
dynamic b = new D();
int? a = c;
dynamic z = a ?? b;
return z;
}
}
";
var compilation = CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(541147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541147")]
[Fact]
public void TestNullCoalesceWithMethodGroup()
{
var source = @"
using System;
static class Program
{
static void Main()
{
Action a = Main ?? Main;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main ?? Main").WithArguments("??", "method group", "method group"));
}
[WorkItem(541149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541149")]
[Fact]
public void TestNullCoalesceWithLambda()
{
var source = @"
using System;
static class Program
{
static void Main()
{
const Action<int> a = null;
var b = a ?? (() => { });
}
}
";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? (() => { })").WithArguments("??", "System.Action<int>", "lambda expression"));
}
[WorkItem(541148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541148")]
[Fact]
public void TestNullCoalesceWithConstNonNullExpression()
{
var source = @"
using System;
static class Program
{
static void Main()
{
const string x = ""A"";
string y;
string z = x ?? y;
Console.WriteLine(z);
}
}
";
CompileAndVerify(source, expectedOutput: "A");
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_01()
{
var source = @"
class B
{
static void Main()
{
A a = null;
B b = null;
var c = a ?? b;
}
public static implicit operator A(B x)
{
return new A();
}
}
class A
{
public static implicit operator A(B x)
{
return new A();
}
public static implicit operator B(A x)
{
return new B();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,22): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c = a ?? b;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_02()
{
var source = @"
struct B
{
static void Main()
{
A? a = null;
B b;
var c = a ?? b;
}
public static implicit operator A(B x)
{
return new A();
}
}
struct A
{
public static implicit operator A(B x)
{
return new A();
}
public static implicit operator B(A x)
{
return new B();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,22): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c = a ?? b;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(545631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545631")]
[Fact]
public void TestNullCoalesceWithInvalidUserDefinedConversions_03()
{
var source = @"
struct B
{
static void Main()
{
A a2;
B? b2 = null;
var c2 = b2 ?? a2;
}
public static implicit operator A(B x)
{
return new A();
}
}
struct A
{
public static implicit operator A(B x)
{
return new A();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,18): error CS0457: Ambiguous user defined conversions 'B.implicit operator A(B)' and 'A.implicit operator A(B)' when converting from 'B' to 'A'
// var c2 = b2 ?? a2;
Diagnostic(ErrorCode.ERR_AmbigUDConv, "b2").WithArguments("B.implicit operator A(B)", "A.implicit operator A(B)", "B", "A"));
}
[WorkItem(541343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541343")]
[Fact]
public void TestAsOperator_Bug8014()
{
var source = @"
using System;
class Program
{
static void Main()
{
object y = null as object ?? null;
}
}
";
CompileAndVerify(source, expectedOutput: string.Empty);
}
[WorkItem(542090, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542090")]
[Fact]
public void TestAsOperatorWithImplicitConversion()
{
var source = @"
using System;
class Program
{
static void Main()
{
object o = 5 as object;
string s = ""str"" as string;
s = null as string;
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[Fact]
public void TestDefaultOperator_ConstantDateTime()
{
var source = @"
using System;
namespace N2
{
class X
{
public static void Main()
{
}
public static DateTime Goo()
{
return default(DateTime);
}
}
}";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestDefaultOperator_Dynamic()
{
// "default(dynamic)" has constant value null.
var source = @"
using System;
public class X
{
public static void Main()
{
const object obj = default(dynamic);
Console.Write(obj == null);
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "True"); ;
source = @"
using System;
public class C<T> { }
public class X
{
public X(dynamic param = default(dynamic)) { Console.WriteLine(param == null); }
public static void Main()
{
Console.Write(default(dynamic));
Console.Write(default(C<dynamic>));
Console.WriteLine(default(dynamic) == null);
Console.WriteLine(default(C<dynamic>) == null);
object x = default(dynamic);
Console.WriteLine(x == null);
var unused = new X();
}
}";
comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics();
// "default(dynamic)" has type dynamic
source = @"
public class X
{
public X(object param = default(dynamic)) {}
}";
comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (4,21): error CS1750: A value of type 'dynamic' cannot be used as a default parameter because there are no standard conversions to type 'object'
// public X(object param = default(dynamic)) {}
Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "param").WithArguments("dynamic", "object"));
}
[WorkItem(537876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537876")]
[Fact]
public void TestEnumOrAssign()
{
var source = @"
enum F
{
A,
B,
C
}
class Program
{
static void Main(string[] args)
{
F x = F.A;
x |= F.B;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542072")]
[Fact]
public void TestEnumLogicalWithLiteralZero_9042()
{
var source = @"
enum F { A }
class Program
{
static void Main()
{
M(F.A | 0);
M(0 | F.A);
M(F.A & 0);
M(0 & F.A);
M(F.A ^ 0);
M(0 ^ F.A);
}
static void M(F f) {}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542073, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542073")]
[Fact]
public void TestEnumCompoundAddition_9043()
{
var source = @"
enum F { A, B }
class Program
{
static void Main()
{
F f = F.A;
f += 1;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[WorkItem(542086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542086")]
[Fact]
public void TestStringCompoundAddition_9146()
{
var source = @"
class Test
{
public static void Main()
{
int i = 0;
string s = ""i="";
s += i;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestOpTrueInBooleanExpression()
{
var source = @"
class Program
{
struct C
{
public int x;
public static bool operator true(C c) { return c.x != 0; }
public static bool operator false(C c) { return c.x == 0; }
public static bool operator true(C? c) { return c.HasValue && c.Value.x != 0; }
public static bool operator false(C? c) { return c.HasValue && c.Value.x == 0; }
}
static void Main()
{
C c = new C();
c.x = 1;
if (c)
{
System.Console.WriteLine(1);
}
while(c)
{
System.Console.WriteLine(2);
c.x--;
}
for(c.x = 1; c; c.x--)
System.Console.WriteLine(3);
c.x = 1;
do
{
System.Console.WriteLine(4);
c.x--;
}
while(c);
System.Console.WriteLine(c ? 6 : 5);
C? c2 = c;
System.Console.WriteLine(c2 ? 7 : 8);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void TestOpTrueInBooleanExpressionError()
{
// operator true does not lift to nullable.
var source = @"
class Program
{
struct C
{
public int x;
public static bool operator true(C c) { return c.x != 0; }
public static bool operator false(C c) { return c.x == 0; }
}
static void Main()
{
C? c = new C();
if (c)
{
System.Console.WriteLine(1);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,13): error CS0029: Cannot implicitly convert type 'Program.C?' to 'bool'
// if (c)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c").WithArguments("Program.C?", "bool"),
// (6,20): warning CS0649: Field 'Program.C.x' is never assigned to, and will always have its default value 0
// public int x;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Program.C.x", "0")
);
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294")]
[Fact()]
public void TestAsOperatorWithTypeParameter()
{
// SPEC: Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:
// SPEC: - An identity (�6.1.1), implicit nullable (�6.1.4), implicit reference (�6.1.6), boxing (�6.1.7),
// SPEC: explicit nullable (�6.2.3), explicit reference (�6.2.4), or unboxing (�6.2.5) conversion exists
// SPEC: from E to T.
// SPEC: - The type of E or T is an open type.
// SPEC: - E is the null literal.
// SPEC VIOLATION: The specification unintentionally allows the case where requirement 2 above:
// SPEC VIOLATION: "The type of E or T is an open type" is true, but type of E is void type, i.e. T is an open type.
// SPEC VIOLATION: Dev10 compiler correctly generates an error for this case and we will maintain compatibility.
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action>();
}
static void Goo<T>() where T : class
{
object o = Main() as T;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (13,20): error CS0039: Cannot convert type 'void' to 'T' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object o = Main() as T;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "Main() as T").WithArguments("void", "T"));
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294")]
[Fact()]
public void TestIsOperatorWithTypeParameter_01()
{
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action>();
}
static void Goo<T>() where T : class
{
bool b = Main() is T;
}
}
";
// NOTE: Dev10 violates the SPEC for this test case and generates
// NOTE: an error ERR_NoExplicitBuiltinConv if the target type
// NOTE: is an open type. According to the specification, the result
// NOTE: is always false, but no compile time error occurs.
// NOTE: We follow the specification and generate WRN_IsAlwaysFalse
// NOTE: instead of an error.
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (13,18): warning CS0184: The given expression is never of the provided ('T') type
// bool b = Main() is T;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "Main() is T").WithArguments("T"));
}
[Fact]
[WorkItem(34679, "https://github.com/dotnet/roslyn/issues/34679")]
public void TestIsOperatorWithTypeParameter_02()
{
var source = @"
class A<T>
{
public virtual void M1<S>(S x) where S : T { }
}
class C : A<int?>
{
static void Main()
{
var x = new C();
int? y = null;
x.M1(y);
x.Test(y);
y = 0;
x.M1(y);
x.Test(y);
}
void Test(int? x)
{
if (x is System.ValueType)
{
System.Console.WriteLine(""Test if"");
}
else
{
System.Console.WriteLine(""Test else"");
}
}
public override void M1<S>(S x)
{
if (x is System.ValueType)
{
System.Console.WriteLine(""M1 if"");
}
else
{
System.Console.WriteLine(""M1 else"");
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput:
@"M1 else
Test else
M1 if
Test if");
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithGenericContainingType()
{
var source = @"
class Program
{
static void Goo<T>(
Outer<T>.C c1, Outer<int>.C c2,
Outer<T>.S s1, Outer<int>.S s2,
Outer<T>.E e1, Outer<int>.E e2)
{
bool b;
b = c1 is Outer<T>.C; // Deferred to runtime - null check.
b = c1 is Outer<int>.C; // Deferred to runtime - null check.
b = c1 is Outer<long>.C; // Deferred to runtime - null check.
b = c2 is Outer<T>.C; // Deferred to runtime - null check.
b = c2 is Outer<int>.C; // Deferred to runtime - null check.
b = c2 is Outer<long>.C; // Always false.
b = s1 is Outer<T>.S; // Always true.
b = s1 is Outer<int>.S; // Deferred to runtime - type unification.
b = s1 is Outer<long>.S; // Deferred to runtime - type unification.
b = s2 is Outer<T>.S; // Deferred to runtime - type unification.
b = s2 is Outer<int>.S; // Always true.
b = s2 is Outer<long>.S; // Always false.
b = e1 is Outer<T>.E; // Always true.
b = e1 is Outer<int>.E; // Deferred to runtime - type unification.
b = e1 is Outer<long>.E; // Deferred to runtime - type unification.
b = e2 is Outer<T>.E; // Deferred to runtime - type unification.
b = e2 is Outer<int>.E; // Always true.
b = e2 is Outer<long>.E; // Always false.
}
}
class Outer<T>
{
public class C { }
public struct S { }
public enum E { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (16,13): warning CS0184: The given expression is never of the provided ('Outer<long>.C') type
// b = c2 is Outer<long>.C; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "c2 is Outer<long>.C").WithArguments("Outer<long>.C").WithLocation(16, 13),
// (18,13): warning CS0183: The given expression is always of the provided ('Outer<T>.S') type
// b = s1 is Outer<T>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s1 is Outer<T>.S").WithArguments("Outer<T>.S").WithLocation(18, 13),
// (23,13): warning CS0183: The given expression is always of the provided ('Outer<int>.S') type
// b = s2 is Outer<int>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s2 is Outer<int>.S").WithArguments("Outer<int>.S").WithLocation(23, 13),
// (24,13): warning CS0184: The given expression is never of the provided ('Outer<long>.S') type
// b = s2 is Outer<long>.S; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "s2 is Outer<long>.S").WithArguments("Outer<long>.S").WithLocation(24, 13),
// (26,13): warning CS0183: The given expression is always of the provided ('Outer<T>.E') type
// b = e1 is Outer<T>.E; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Outer<T>.E").WithArguments("Outer<T>.E").WithLocation(26, 13),
// (31,13): warning CS0183: The given expression is always of the provided ('Outer<int>.E') type
// b = e2 is Outer<int>.E; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Outer<int>.E").WithArguments("Outer<int>.E").WithLocation(31, 13),
// (32,13): warning CS0184: The given expression is never of the provided ('Outer<long>.E') type
// b = e2 is Outer<long>.E; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "e2 is Outer<long>.E").WithArguments("Outer<long>.E").WithLocation(32, 13));
}
[Fact]
public void TestIsOperatorWithGenericClassAndValueType()
{
var source = @"
class Program
{
static bool Goo<T>(C<T> c)
{
return c is int; // always false
}
}
class C<T> { }
";
CreateCompilation(source).VerifyDiagnostics(
// (6,16): warning CS0184: The given expression is never of the provided ('int') type
// return c is int; // always false
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "c is int").WithArguments("int").WithLocation(6, 16)
);
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithTypesThatCannotUnify()
{
var source = @"
class Program
{
static void Goo<T>(Outer<T>.S s1, Outer<T[]>.S s2)
{
bool b;
b = s1 is Outer<int[]>.S; // T -> int[]
b = s1 is Outer<T[]>.S; // Cannot unify - as in dev12, we do not warn.
b = s2 is Outer<int[]>.S; // T -> int
b = s2 is Outer<T[]>.S; // Always true.
b = s2 is Outer<T[,]>.S; // Cannot unify - as in dev12, we do not warn.
}
}
class Outer<T>
{
public struct S { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (11,13): warning CS0183: The given expression is always of the provided ('Outer<T[]>.S') type
// b = s2 is Outer<T[]>.S; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "s2 is Outer<T[]>.S").WithArguments("Outer<T[]>.S").WithLocation(11, 13));
}
[WorkItem(844635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844635")]
[Fact()]
public void TestIsOperatorWithSpecialTypes()
{
var source = @"
using System;
class Program
{
static void Goo<T, TClass, TStruct>(Outer<T>.E e1, Outer<int>.E e2, int i, T t, TClass tc, TStruct ts)
where TClass : class
where TStruct : struct
{
bool b;
b = e1 is Enum; // Always true.
b = e2 is Enum; // Always true.
b = 0 is Enum; // Always false.
b = i is Enum; // Always false.
b = t is Enum; // Deferred.
b = tc is Enum; // Deferred.
b = ts is Enum; // Deferred.
b = e1 is ValueType; // Always true.
b = e2 is ValueType; // Always true.
b = 0 is ValueType; // Always true.
b = i is ValueType; // Always true.
b = t is ValueType; // Deferred - null check.
b = tc is ValueType; // Deferred - null check.
b = ts is ValueType; // Always true.
b = e1 is Object; // Always true.
b = e2 is Object; // Always true.
b = 0 is Object; // Always true.
b = i is Object; // Always true.
b = t is Object; // Deferred - null check.
b = tc is Object; // Deferred - null check.
b = ts is Object; // Always true.
}
}
class Outer<T>
{
public enum E { }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (11,13): warning CS0183: The given expression is always of the provided ('System.Enum') type
// b = e1 is Enum; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Enum").WithArguments("System.Enum").WithLocation(11, 13),
// (12,13): warning CS0183: The given expression is always of the provided ('System.Enum') type
// b = e2 is Enum; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Enum").WithArguments("System.Enum").WithLocation(12, 13),
// (13,13): warning CS0184: The given expression is never of the provided ('System.Enum') type
// b = 0 is Enum; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "0 is Enum").WithArguments("System.Enum").WithLocation(13, 13),
// (14,13): warning CS0184: The given expression is never of the provided ('System.Enum') type
// b = i is Enum; // Always false.
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "i is Enum").WithArguments("System.Enum").WithLocation(14, 13),
// (19,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = e1 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is ValueType").WithArguments("System.ValueType").WithLocation(19, 13),
// (20,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = e2 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is ValueType").WithArguments("System.ValueType").WithLocation(20, 13),
// (21,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = 0 is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "0 is ValueType").WithArguments("System.ValueType").WithLocation(21, 13),
// (22,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = i is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "i is ValueType").WithArguments("System.ValueType").WithLocation(22, 13),
// (25,13): warning CS0183: The given expression is always of the provided ('System.ValueType') type
// b = ts is ValueType; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "ts is ValueType").WithArguments("System.ValueType").WithLocation(25, 13),
// (27,13): warning CS0183: The given expression is always of the provided ('object') type
// b = e1 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e1 is Object").WithArguments("object").WithLocation(27, 13),
// (28,13): warning CS0183: The given expression is always of the provided ('object') type
// b = e2 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "e2 is Object").WithArguments("object").WithLocation(28, 13),
// (29,13): warning CS0183: The given expression is always of the provided ('object') type
// b = 0 is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "0 is Object").WithArguments("object").WithLocation(29, 13),
// (30,13): warning CS0183: The given expression is always of the provided ('object') type
// b = i is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "i is Object").WithArguments("object").WithLocation(30, 13),
// (33,13): warning CS0183: The given expression is always of the provided ('object') type
// b = ts is Object; // Always true.
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "ts is Object").WithArguments("object").WithLocation(33, 13));
}
[WorkItem(543294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543294"), WorkItem(546655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546655")]
[Fact()]
public void TestAsOperator_SpecErrorCase()
{
// SPEC: Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:
// SPEC: - An identity (�6.1.1), implicit nullable (�6.1.4), implicit reference (�6.1.6), boxing (�6.1.7),
// SPEC: explicit nullable (�6.2.3), explicit reference (�6.2.4), or unboxing (�6.2.5) conversion exists
// SPEC: from E to T.
// SPEC: - The type of E or T is an open type.
// SPEC: - E is the null literal.
// SPEC VIOLATION: The specification contains an error in the list of legal conversions above.
// SPEC VIOLATION: If we have "class C<T, U> where T : U where U : class" then there is
// SPEC VIOLATION: an implicit conversion from T to U, but it is not an identity, reference or
// SPEC VIOLATION: boxing conversion. It will be one of those at runtime, but at compile time
// SPEC VIOLATION: we do not know which, and therefore cannot classify it as any of those.
var source = @"
using System;
class Program
{
static void Main()
{
Goo<Action, Action>(null);
}
static U Goo<T, U>(T t)
where T : U
where U : class
{
var s = t is U;
return t as U;
}
}
";
CompileAndVerify(source, expectedOutput: "").VerifyDiagnostics();
}
[WorkItem(546655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546655")]
[Fact()]
public void TestIsOperatorWithTypeParameter_Bug16461()
{
var source = @"
using System;
public class G<T>
{
public bool M(T t) { return t is object; }
}
public class GG<T, V> where T : V
{
public bool M(T t) { return t is V; }
}
class Test
{
static void Main()
{
var obj = new G<Test>();
Console.WriteLine(obj.M( (Test)null ));
var obj1 = new GG<Test, Test>();
Console.WriteLine(obj1.M( (Test)null ));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"False
False");
comp.VerifyDiagnostics();
}
[Fact()]
public void TestIsAsOperator_UserDefinedConversionsNotAllowed()
{
var source = @"
// conversion.cs
class Goo { public Goo(Bar b){} }
class Goo2 { public Goo2(Bar b){} }
struct Bar
{
// Declare an implicit conversion from a int to a Bar
static public implicit operator Bar(int value)
{
return new Bar();
}
// Declare an explicit conversion from a Bar to Goo
static public explicit operator Goo(Bar value)
{
return new Goo(value);
}
// Declare an implicit conversion from a Bar to Goo2
static public implicit operator Goo2(Bar value)
{
return new Goo2(value);
}
}
class Test
{
static public void Main()
{
Bar numeral;
numeral = 10;
object a1 = numeral as Goo;
object a2 = 1 as Bar;
object a3 = numeral as Goo2;
bool b1 = numeral is Goo;
bool b2 = 1 is Bar;
bool b3 = numeral is Goo2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (37,21): error CS0039: Cannot convert type 'Bar' to 'Goo' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object a1 = numeral as Goo;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "numeral as Goo").WithArguments("Bar", "Goo"),
// (38,21): error CS0077: The as operator must be used with a reference type or nullable type ('Bar' is a non-nullable value type)
// object a2 = 1 as Bar;
Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "1 as Bar").WithArguments("Bar"),
// (39,21): error CS0039: Cannot convert type 'Bar' to 'Goo2' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
// object a3 = numeral as Goo2;
Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "numeral as Goo2").WithArguments("Bar", "Goo2"),
// (41,19): warning CS0184: The given expression is never of the provided ('Goo') type
// bool b1 = numeral is Goo;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "numeral is Goo").WithArguments("Goo"),
// (42,19): warning CS0184: The given expression is never of the provided ('Bar') type
// bool b2 = 1 is Bar;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is Bar").WithArguments("Bar"),
// (43,19): warning CS0184: The given expression is never of the provided ('Goo2') type
// bool b3 = numeral is Goo2;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "numeral is Goo2").WithArguments("Goo2"));
}
[WorkItem(543455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543455")]
[Fact()]
public void CS0184WRN_IsAlwaysFalse_Generic()
{
var text = @"
public class GenC<T> : GenI<T> where T : struct
{
public bool Test(T t)
{
return (t is C);
}
}
public interface GenI<T>
{
bool Test(T t);
}
public class C
{
public void Method() { }
public static int Main()
{
return 0;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is C").WithArguments("C"));
}
[WorkItem(547011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547011")]
[Fact()]
public void CS0184WRN_IsAlwaysFalse_IntPtr()
{
var text = @"using System;
public enum E
{
First
}
public class Base
{
public static void Main()
{
E e = E.First;
Console.WriteLine(e is IntPtr);
Console.WriteLine(e as IntPtr);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (12,27): warning CS0184: The given expression is never of the provided ('System.IntPtr') type
// Console.WriteLine(e is IntPtr);
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "e is IntPtr").WithArguments("System.IntPtr"),
// (13,27): error CS0077: The as operator must be used with a reference type or nullable type ('System.IntPtr' is a non-nullable value type)
// Console.WriteLine(e as IntPtr);
Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "e as IntPtr").WithArguments("System.IntPtr"));
}
[WorkItem(543443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543443")]
[Fact]
public void ParamsOperators()
{
var text =
@"class X
{
public static bool operator >(X a, params int[] b)
{
return true;
}
public static bool operator <(X a, params int[] b)
{
return false;
}
}";
CreateCompilation(text).VerifyDiagnostics(
// (3,39): error CS1670: params is not valid in this context public static bool operator >(X a, params int[] b)
Diagnostic(ErrorCode.ERR_IllegalParams, "params"),
// (8,40): error CS1670: params is not valid in this context
// public static bool operator <(X a, params int[] b)
Diagnostic(ErrorCode.ERR_IllegalParams, "params")
);
}
[WorkItem(543438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543438")]
[Fact()]
public void TestNullCoalesce_UserDefinedConversions()
{
var text =
@"class B
{
static void Main()
{
A a = null;
B b = null;
var c = a ?? b;
}
}
class A
{
public static implicit operator B(A x)
{
return new B();
}
}";
CompileAndVerify(text);
}
[WorkItem(543503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543503")]
[Fact()]
public void TestAsOperator_UserDefinedConversions()
{
var text =
@"using System;
class C<T>
{
public static implicit operator string (C<T> x)
{
return """";
}
string s = new C<T>() as string;
}";
CompileAndVerify(text);
}
[WorkItem(543503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543503")]
[Fact()]
public void TestIsOperator_UserDefinedConversions()
{
var text =
@"using System;
class C<T>
{
public static implicit operator string (C<T> x)
{
return """";
}
bool b = new C<T>() is string;
}";
CompileAndVerify(text);
}
[WorkItem(543483, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543483")]
[Fact]
public void TestEqualityOperator_NullableStructs()
{
string source1 =
@"
public struct NonGenericStruct { }
public struct GenericStruct<T> { }
public class Goo
{
public NonGenericStruct? ngsq;
public GenericStruct<int>? gsiq;
}
public class GenGoo<T>
{
public GenericStruct<T>? gstq;
}
public class Test
{
public static bool Run()
{
Goo f = new Goo();
f.ngsq = new NonGenericStruct();
f.gsiq = new GenericStruct<int>();
GenGoo<int> gf = new GenGoo<int>();
gf.gstq = new GenericStruct<int>();
return (f.ngsq != null) && (f.gsiq != null) && (gf.gstq != null);
}
public static void Main()
{
System.Console.WriteLine(Run() ? 1 : 0);
}
}";
string source2 = @"
struct S
{
public static bool operator ==(S? x, decimal? y) { return false; }
public static bool operator !=(S? x, decimal? y) { return false; }
public static bool operator ==(S? x, double? y) { return false; }
public static bool operator !=(S? x, double? y) { return false; }
public override int GetHashCode() { return 0; }
public override bool Equals(object x) { return false; }
static void Main()
{
S? s = default(S?);
// This is *not* equivalent to !s.HasValue because
// there is an applicable user-defined conversion.
// Even though the conversion is ambiguous!
if (s == null) s = default(S);
}
}
";
CompileAndVerify(source1, expectedOutput: "1");
CreateCompilation(source2).VerifyDiagnostics(
// (16,9): error CS0034: Operator '==' is ambiguous on operands of type 'S?' and '<null>'
// if (s == null) s = default(S);
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "s == null").WithArguments("==", "S?", "<null>"));
}
[WorkItem(543432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543432")]
[Fact]
public void NoNewForOperators()
{
var text =
@"class A
{
public static implicit operator A(D x)
{
return null;
}
}
class B : A
{
public static implicit operator B(D x)
{
return null;
}
}
class D {}";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact(), WorkItem(543433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543433")]
public void ERR_NoImplicitConvCast_UserDefinedConversions()
{
var text =
@"class A
{
public static A operator ++(A x)
{
return new A();
}
}
class B : A
{
static void Main()
{
B b = new B();
b++;
}
}
";
CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b++").WithArguments("A", "B"));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorIncrement()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static (T1 fst, T2 snd) operator ++((T1 one, T2 two) tuple)
{
return tuple;
}
}
}
";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorConvert()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static explicit operator (T1 fst, T2 snd)((T1 one, T2 two) s)
{
return s;
}
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,41): error CS0555: User-defined operator cannot convert a type to itself
// public static explicit operator (T1 fst, T2 snd)((T1 one, T2 two) s)
Diagnostic(ErrorCode.ERR_IdentityConversion, "(T1 fst, T2 snd)").WithLocation(6, 41));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleOperatorConvertToBaseType()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static explicit operator ValueType(ValueTuple<T1, T2> s)
{
return s;
}
}
}
";
CreateCompilation(text).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(
// (6,41): error CS0553: '(T1, T2).explicit operator ValueType((T1, T2))': user-defined conversions to or from a base type are not allowed
// public static explicit operator ValueType(ValueTuple<T1, T2> s)
Diagnostic(ErrorCode.ERR_ConversionWithBase, "ValueType").WithArguments("(T1, T2).explicit operator System.ValueType((T1, T2))").WithLocation(6, 41));
}
[Fact, WorkItem(30668, "https://github.com/dotnet/roslyn/issues/30668")]
public void TestTupleBinaryOperator()
{
var text = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public static ValueTuple<T1, T2> operator +((T1 fst, T2 snd) s1, (T1 one, T2 two) s2)
{
return s1;
}
}
}
";
CreateCompilation(text).GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_01()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
string expectedOutput = @"True
False";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_02()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((Func<int>)(C)null == (D)null);
Console.WriteLine((Func<int>)(C)null == (Action)(D)null);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (21,27): error CS0019: Operator '==' cannot be applied to operands of type 'System.Func<int>' and 'D'
// Console.WriteLine((Func<int>)(C)null == (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(Func<int>)(C)null == (D)null").WithArguments("==", "System.Func<int>", "D"),
// (22,27): error CS0019: Operator '==' cannot be applied to operands of type 'System.Func<int>' and 'System.Action'
// Console.WriteLine((Func<int>)(C)null == (Action)(D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(Func<int>)(C)null == (Action)(D)null").WithArguments("==", "System.Func<int>", "System.Action"));
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_03_Ambiguous()
{
string source =
@"
using System;
class C
{
public static implicit operator Func<int>(C x)
{
return null;
}
}
class D
{
public static implicit operator Action(D x)
{
return null;
}
public static implicit operator Func<int>(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (26,27): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'D'
// Console.WriteLine((C)null == (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(C)null == (D)null").WithArguments("==", "C", "D"),
// (27,27): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'D'
// Console.WriteLine((C)null != (D)null);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(C)null != (D)null").WithArguments("!=", "C", "D"));
}
[WorkItem(543431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543431")]
[Fact]
public void TestEqualityOperator_DelegateTypes_04_BaseTypes()
{
string source =
@"
using System;
class A
{
public static implicit operator Func<int>(A x)
{
return null;
}
}
class C : A
{
}
class D
{
public static implicit operator Func<int>(D x)
{
return null;
}
static void Main()
{
Console.WriteLine((C)null == (D)null);
Console.WriteLine((C)null != (D)null);
}
}
";
string expectedOutput = @"True
False";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[WorkItem(543754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543754")]
[Fact]
public void TestEqualityOperator_NullableDecimal()
{
string source =
@"
public class Test
{
public static bool Goo(decimal? deq)
{
return deq == null;
}
public static void Main()
{
Goo(null);
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[WorkItem(543910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543910")]
[Fact]
public void TypeParameterConstraintToGenericType()
{
string source =
@"
public class Gen<T>
{
public T t;
public Gen(T t)
{
this.t = t;
}
public static Gen<T> operator + (Gen<T> x, T y)
{
return new Gen<T>(y);
}
}
public class ConstrainedTestContext<T,U> where T : Gen<U>
{
public static Gen<U> ExecuteOpAddition(T x, U y)
{
return x + y;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(544490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544490")]
[Fact]
public void LiftedUserDefinedUnaryOperator()
{
string source =
@"
struct S
{
public static int operator +(S s) { return 1; }
public static void Main()
{
S s = new S();
S? sq = s;
var j = +sq;
System.Console.WriteLine(j);
}
}
";
CompileAndVerify(source, expectedOutput: "1");
}
[WorkItem(544490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544490")]
[Fact]
public void TestDefaultOperatorEnumConstantValue()
{
string source =
@"
enum X { F = 0 };
class C
{
public static int Main()
{
const X x = default(X);
return (int)x;
}
}
";
CompileAndVerify(source, expectedOutput: "");
}
[Fact]
public void OperatorHiding1()
{
string source = @"
class Base1
{
public static Base1 operator +(Base1 b, Derived1 d) { return b; }
}
class Derived1 : Base1
{
public static Base1 operator +(Base1 b, Derived1 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding2()
{
string source = @"
class Base2
{
public static Base2 op_Addition(Base2 b, Derived2 d) { return b; }
}
class Derived2 : Base2
{
public static Base2 operator +(Base2 b, Derived2 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding3()
{
string source = @"
class Base3
{
public static Base3 operator +(Base3 b, Derived3 d) { return b; }
}
class Derived3 : Base3
{
public static Base3 op_Addition(Base3 b, Derived3 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void OperatorHiding4()
{
string source = @"
class Base4
{
public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
}
class Derived4 : Base4
{
public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,25): warning CS0108: 'Derived4.op_Addition(Base4, Derived4)' hides inherited member 'Base4.op_Addition(Base4, Derived4)'. Use the new keyword if hiding was intended.
// public static Base4 op_Addition(Base4 b, Derived4 d) { return b; }
Diagnostic(ErrorCode.WRN_NewRequired, "op_Addition").WithArguments("Derived4.op_Addition(Base4, Derived4)", "Base4.op_Addition(Base4, Derived4)"));
}
[Fact]
public void ConversionHiding1()
{
string source = @"
class Base1
{
public static implicit operator string(Base1 b) { return null; }
}
class Derived1 : Base1
{
public static implicit operator string(Base1 b) { return null; } // CS0556, but not CS0108
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,37): error CS0556: User-defined conversion must convert to or from the enclosing type
// public static implicit operator string(Base1 b) { return null; }
Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "string"));
}
[Fact]
public void ConversionHiding2()
{
string source = @"
class Base2
{
public static string op_Explicit(Derived2 d) { return null; }
}
class Derived2 : Base2
{
public static implicit operator string(Derived2 d) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ConversionHiding3()
{
string source = @"
class Base3
{
public static implicit operator string(Base3 b) { return null; }
}
class Derived3 : Base3
{
public static string op_Explicit(Base3 b) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ConversionHiding4()
{
string source = @"
class Base4
{
public static string op_Explicit(Base4 b) { return null; }
}
class Derived4 : Base4
{
public static string op_Explicit(Base4 b) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,26): warning CS0108: 'Derived4.op_Explicit(Base4)' hides inherited member 'Base4.op_Explicit(Base4)'. Use the new keyword if hiding was intended.
// public static string op_Explicit(Base4 b) { return null; }
Diagnostic(ErrorCode.WRN_NewRequired, "op_Explicit").WithArguments("Derived4.op_Explicit(Base4)", "Base4.op_Explicit(Base4)"));
}
[Fact]
public void ClassesWithOperatorNames()
{
string source = @"
class op_Increment
{
public static op_Increment operator ++ (op_Increment c) { return null; }
}
class op_Decrement
{
public static op_Decrement operator -- (op_Decrement c) { return null; }
}
class op_UnaryPlus
{
public static int operator + (op_UnaryPlus c) { return 0; }
}
class op_UnaryNegation
{
public static int operator - (op_UnaryNegation c) { return 0; }
}
class op_OnesComplement
{
public static int operator ~ (op_OnesComplement c) { return 0; }
}
class op_Addition
{
public static int operator + (op_Addition c, int i) { return 0; }
}
class op_Subtraction
{
public static int operator - (op_Subtraction c, int i) { return 0; }
}
class op_Multiply
{
public static int operator * (op_Multiply c, int i) { return 0; }
}
class op_Division
{
public static int operator / (op_Division c, int i) { return 0; }
}
class op_Modulus
{
public static int operator % (op_Modulus c, int i) { return 0; }
}
class op_ExclusiveOr
{
public static int operator ^ (op_ExclusiveOr c, int i) { return 0; }
}
class op_BitwiseAnd
{
public static int operator & (op_BitwiseAnd c, int i) { return 0; }
}
class op_BitwiseOr
{
public static int operator | (op_BitwiseOr c, int i) { return 0; }
}
class op_LeftShift
{
public static long operator << (op_LeftShift c, int i) { return 0; }
}
class op_RightShift
{
public static long operator >> (op_RightShift c, int i) { return 0; }
}
class op_UnsignedRightShift
{
}
";
CreateCompilation(source).VerifyDiagnostics(
// (4,38): error CS0542: 'op_Increment': member names cannot be the same as their enclosing type
// public static op_Increment operator ++ (op_Increment c) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "++").WithArguments("op_Increment"),
// (8,38): error CS0542: 'op_Decrement': member names cannot be the same as their enclosing type
// public static op_Decrement operator -- (op_Decrement c) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "--").WithArguments("op_Decrement"),
// (12,29): error CS0542: 'op_UnaryPlus': member names cannot be the same as their enclosing type
// public static int operator + (op_UnaryPlus c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "+").WithArguments("op_UnaryPlus"),
// (16,39): error CS0542: 'op_UnaryNegation': member names cannot be the same as their enclosing type
// public static int operator - (op_UnaryNegation c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "-").WithArguments("op_UnaryNegation"),
// (20,29): error CS0542: 'op_OnesComplement': member names cannot be the same as their enclosing type
// public static int operator ~ (op_OnesComplement c) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "~").WithArguments("op_OnesComplement"),
// (24,29): error CS0542: 'op_Addition': member names cannot be the same as their enclosing type
// public static int operator + (op_Addition c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "+").WithArguments("op_Addition"),
// (28,29): error CS0542: 'op_Subtraction': member names cannot be the same as their enclosing type
// public static int operator - (op_Subtraction c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "-").WithArguments("op_Subtraction"),
// (32,29): error CS0542: 'op_Multiply': member names cannot be the same as their enclosing type
// public static int operator * (op_Multiply c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "*").WithArguments("op_Multiply"),
// (36,29): error CS0542: 'op_Division': member names cannot be the same as their enclosing type
// public static int operator / (op_Division c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "/").WithArguments("op_Division"),
// (40,29): error CS0542: 'op_Modulus': member names cannot be the same as their enclosing type
// public static int operator % (op_Modulus c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "%").WithArguments("op_Modulus"),
// (44,29): error CS0542: 'op_ExclusiveOr': member names cannot be the same as their enclosing type
// public static int operator ^ (op_ExclusiveOr c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "^").WithArguments("op_ExclusiveOr"),
// (48,29): error CS0542: 'op_BitwiseAnd': member names cannot be the same as their enclosing type
// public static int operator & (op_BitwiseAnd c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "&").WithArguments("op_BitwiseAnd"),
// (52,29): error CS0542: 'op_BitwiseOr': member names cannot be the same as their enclosing type
// public static int operator | (op_BitwiseOr c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "|").WithArguments("op_BitwiseOr"),
// (56,30): error CS0542: 'op_LeftShift': member names cannot be the same as their enclosing type
// public static long operator << (op_LeftShift c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "<<").WithArguments("op_LeftShift"),
// (60,30): error CS0542: 'op_RightShift': member names cannot be the same as their enclosing type
// public static long operator >> (op_RightShift c, int i) { return 0; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, ">>").WithArguments("op_RightShift"));
}
[Fact]
public void ClassesWithConversionNames()
{
string source = @"
class op_Explicit
{
public static explicit operator op_Explicit(int x) { return null; }
}
class op_Implicit
{
public static implicit operator op_Implicit(int x) { return null; }
}
";
CreateCompilation(source).VerifyDiagnostics(
// (4,37): error CS0542: 'op_Explicit': member names cannot be the same as their enclosing type
// public static explicit operator op_Explicit(int x) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "op_Explicit").WithArguments("op_Explicit"),
// (9,37): error CS0542: 'op_Implicit': member names cannot be the same as their enclosing type
// public static implicit operator op_Implicit(int x) { return null; }
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "op_Implicit").WithArguments("op_Implicit"));
}
[Fact, WorkItem(546771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546771")]
public void TestIsNullable_Bug16777()
{
string source = @"
class Program
{
enum E { }
static void Main()
{
M(null);
M(0);
}
static void M(E? e)
{
System.Console.Write(e is E ? 't' : 'f');
}
}
";
CompileAndVerify(source: source, expectedOutput: "ft");
}
[Fact]
public void CompoundOperatorWithThisOnLeft()
{
string source =
@"using System;
public struct Value
{
int value;
public Value(int value)
{
this.value = value;
}
public static Value operator +(Value a, int b)
{
return new Value(a.value + b);
}
public void Test()
{
this += 2;
}
public void Print()
{
Console.WriteLine(this.value);
}
public static void Main(string[] args)
{
Value v = new Value(1);
v.Test();
v.Print();
}
}";
string output = @"3";
CompileAndVerify(source: source, expectedOutput: output);
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality1()
{
string source = @"
struct S1
{
// Interesting
public static bool operator ==(S1 x, S1 y) { throw null; }
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S1 y) { throw null; }
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1)
{
return s1 == null;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var expectedOperator = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("S1").GetMembers(WellKnownMemberNames.EqualityOperatorName).
OfType<MethodSymbol>().Single(m => m.ParameterTypesWithAnnotations[0].Equals(m.ParameterTypesWithAnnotations[1], TypeCompareKind.ConsiderEverything));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
var info = model.GetSymbolInfo(syntax);
Assert.Equal(expectedOperator.GetPublicSymbol(), info.Symbol);
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality2()
{
string source = @"
using System;
struct S1
{
// Interesting
[Obsolete(""A"")]
public static bool operator ==(S1 x, S1 y) { throw null; }
[Obsolete(""B"")]
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S1 y) { throw null; }
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1)
{
return s1 == null;
}
}
";
// CONSIDER: This is a little silly, since that method will never be called.
CreateCompilation(source).VerifyDiagnostics(
// (27,16): warning CS0618: 'S1.operator ==(S1, S1)' is obsolete: 'A'
// return s1 == null;
Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "s1 == null").WithArguments("S1.operator ==(S1, S1)", "A"));
}
[WorkItem(631414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/631414")]
[Fact]
public void LiftedUserDefinedEquality3()
{
string source = @"
struct S1
{
// Interesting
public static bool operator ==(S1 x, S2 y) { throw null; }
// Filler
public static bool operator !=(S1 x, S2 y) { throw null; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
}
struct S2
{
}
class Program
{
bool Test(S1? s1, S2? s2)
{
return s1 == s2;
}
}
";
// CONSIDER: There is no reason not to allow this, but dev11 doesn't.
CreateCompilation(source).VerifyDiagnostics(
// (21,16): error CS0019: Operator '==' cannot be applied to operands of type 'S1?' and 'S2?'
// return s1 == s2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "s1 == s2").WithArguments("==", "S1?", "S2?"));
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void AmbiguousLogicalOrConversion()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
// SPEC VIOLATION: According to the spec, this is ambiguous. However, we will match the dev11 behavior.
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("i2", syntax.Identifier.ValueText);
var info = model.GetTypeInfo(syntax);
Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("InputParameter"), info.Type.GetSymbol());
Assert.Equal(comp.GetSpecialType(SpecialType.System_Boolean), info.ConvertedType.GetSymbol());
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void AmbiguousOrConversion()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 | i2;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (21,18): error CS0034: Operator '|' is ambiguous on operands of type 'InputParameter' and 'InputParameter'
// bool b = i1 | i2;
Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "i1 | i2").WithArguments("|", "InputParameter", "InputParameter"));
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void DynamicAmbiguousLogicalOrConversion()
{
string source = @"
using System;
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
System.Console.WriteLine(""A"");
return true;
}
public static implicit operator int(InputParameter inputParameter)
{
System.Console.WriteLine(""B"");
return 1;
}
}
class Program
{
static void Main(string[] args)
{
dynamic i1 = new InputParameter();
dynamic i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: @"A
A");
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[ConditionalFact(typeof(DesktopOnly))]
public void DynamicAmbiguousOrConversion()
{
string source = @"
using System;
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
System.Console.WriteLine(""A"");
return true;
}
public static implicit operator int(InputParameter inputParameter)
{
System.Console.WriteLine(""B"");
return 1;
}
}
class Program
{
static void Main(string[] args)
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
dynamic i1 = new InputParameter();
dynamic i2 = new InputParameter();
bool b = i1 | i2;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.ReleaseExe);
CompileAndVerifyException<Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>(comp,
"Operator '|' is ambiguous on operands of type 'InputParameter' and 'InputParameter'");
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void UnambiguousLogicalOrConversion1()
{
string source = @"
class InputParameter
{
public static implicit operator bool(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var syntax = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Last();
Assert.Equal("i2", syntax.Identifier.ValueText);
var info = model.GetTypeInfo(syntax);
Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("InputParameter").GetPublicSymbol(), info.Type);
Assert.Equal(comp.GetSpecialType(SpecialType.System_Boolean).GetPublicSymbol(), info.ConvertedType);
}
[WorkItem(656739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656739")]
[Fact]
public void UnambiguousLogicalOrConversion2()
{
string source = @"
class InputParameter
{
public static implicit operator int(InputParameter inputParameter)
{
throw null;
}
}
class Program
{
static void Main(string[] args)
{
InputParameter i1 = new InputParameter();
InputParameter i2 = new InputParameter();
bool b = i1 || i2;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (16,18): error CS0019: Operator '||' cannot be applied to operands of type 'InputParameter' and 'InputParameter'
// bool b = i1 || i2;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "i1 || i2").WithArguments("||", "InputParameter", "InputParameter"));
}
[WorkItem(665002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665002")]
[Fact]
public void DedupingLiftedUserDefinedOperators()
{
string source = @"
using System;
public class RubyTime
{
public static TimeSpan operator -(RubyTime x, DateTime y)
{
throw null;
}
public static TimeSpan operator -(RubyTime x, RubyTime y)
{
throw null;
}
public static implicit operator DateTime(RubyTime time)
{
throw null;
}
TimeSpan Test(RubyTime x, DateTime y)
{
return x - y;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
/// <summary>
/// Verify operators returned from BinaryOperatorEasyOut match
/// the operators found from overload resolution.
/// </summary>
[Fact]
public void BinaryOperators_EasyOut()
{
var source =
@"class Program
{
static T F<T>() => throw null;
static void Main()
{
F<object>();
F<string>();
F<bool>();
F<char>();
F<sbyte>();
F<short>();
F<int>();
F<long>();
F<byte>();
F<ushort>();
F<uint>();
F<ulong>();
F<nint>();
F<nuint>();
F<float>();
F<double>();
F<decimal>();
F<bool?>();
F<char?>();
F<sbyte?>();
F<short?>();
F<int?>();
F<long?>();
F<byte?>();
F<ushort?>();
F<uint?>();
F<ulong?>();
F<nint?>();
F<nuint?>();
F<float?>();
F<double?>();
F<decimal?>();
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var syntax = tree.GetRoot();
var methodBody = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Last().Body;
var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(methodBody.SpanStart);
var diagnostics = DiagnosticBag.GetInstance();
var block = binder.BindEmbeddedBlock(methodBody, diagnostics);
diagnostics.Free();
var exprs = block.Statements.SelectAsArray(stmt => ((BoundExpressionStatement)stmt).Expression);
Assert.Equal(32, exprs.Length);
var operators = new[]
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Equal,
BinaryOperatorKind.NotEqual,
BinaryOperatorKind.Or,
BinaryOperatorKind.And,
BinaryOperatorKind.Xor,
};
foreach (var op in operators)
{
foreach (var left in exprs)
{
foreach (var right in exprs)
{
var signature1 = getBinaryOperator(binder, op, left, right, useEasyOut: true);
var signature2 = getBinaryOperator(binder, op, left, right, useEasyOut: false);
Assert.Equal(signature1, signature2);
}
}
}
static BinaryOperatorKind getBinaryOperator(Binder binder, BinaryOperatorKind kind, BoundExpression left, BoundExpression right, bool useEasyOut)
{
var overloadResolution = new OverloadResolution(binder);
var result = BinaryOperatorOverloadResolutionResult.GetInstance();
if (useEasyOut)
{
overloadResolution.BinaryOperatorOverloadResolution_EasyOut(kind, left, right, result);
}
else
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
overloadResolution.BinaryOperatorOverloadResolution_NoEasyOut(kind, left, right, result, ref discardedUseSiteInfo);
}
var signature = result.Best.Signature.Kind;
result.Free();
return signature;
}
}
[Fact()]
public void UnaryIntrinsicSymbols1()
{
UnaryOperatorKind[] operators =
{
UnaryOperatorKind.PostfixIncrement,
UnaryOperatorKind.PostfixDecrement,
UnaryOperatorKind.PrefixIncrement,
UnaryOperatorKind.PrefixDecrement,
UnaryOperatorKind.UnaryPlus,
UnaryOperatorKind.UnaryMinus,
UnaryOperatorKind.LogicalNegation,
UnaryOperatorKind.BitwiseComplement
};
string[] opTokens = {"++","--","++","--",
"+","-","!","~"};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"dynamic",
"byte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{1}({0} x1, System.Nullable<{0}> x2)\n", arg1, n);
builder.Append(
"{\n");
for (int k = 0; k < operators.Length; k++)
{
if (operators[k] == UnaryOperatorKind.PostfixDecrement || operators[k] == UnaryOperatorKind.PostfixIncrement)
{
builder.AppendFormat(
" var z{0}_1 = x1 {1};\n" +
" var z{0}_2 = x2 {1};\n" +
" if (x1 {1}) {{}}\n" +
" if (x2 {1}) {{}}\n",
k, opTokens[k]);
}
else
{
builder.AppendFormat(
" var z{0}_1 = {1} x1;\n" +
" var z{0}_2 = {1} x2;\n" +
" if ({1} x1) {{}}\n" +
" if ({1} x2) {{}}\n",
k, opTokens[k]);
}
}
builder.Append(
"}\n");
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select ((ExpressionSyntax)(node as PrefixUnaryExpressionSyntax)) ?? node as PostfixUnaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
n = 0;
for (int name = 0; name < typeNames.Length; name++)
{
TypeSymbol type;
if (name == typeNames.Length - 1)
{
type = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
}
else if (name == typeNames.Length - 2)
{
type = compilation.DynamicType;
}
else
{
type = compilation.GetTypeByMetadataName(typeNames[name]);
}
foreach (var op in operators)
{
TestUnaryIntrinsicSymbol(
op,
type,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3]);
n += 4;
}
}
Assert.Equal(n, nodes.Length);
}
private void TestUnaryIntrinsicSymbol(
UnaryOperatorKind op,
TypeSymbol type,
CSharpCompilation compilation,
SemanticModel semanticModel,
ExpressionSyntax node1,
ExpressionSyntax node2,
ExpressionSyntax node3,
ExpressionSyntax node4
)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
Assert.Equal(type.IsDynamic() ? CandidateReason.LateBound : CandidateReason.None, info1.CandidateReason);
Assert.Equal(0, info1.CandidateSymbols.Length);
var symbol1 = (IMethodSymbol)info1.Symbol;
var symbol2 = semanticModel.GetSymbolInfo(node2).Symbol;
var symbol3 = (IMethodSymbol)semanticModel.GetSymbolInfo(node3).Symbol;
var symbol4 = semanticModel.GetSymbolInfo(node4).Symbol;
Assert.Equal(symbol1, symbol3);
if ((object)symbol1 != null)
{
Assert.NotSame(symbol1, symbol3);
Assert.Equal(symbol1.GetHashCode(), symbol3.GetHashCode());
Assert.Equal(symbol1.Parameters[0], symbol3.Parameters[0]);
Assert.Equal(symbol1.Parameters[0].GetHashCode(), symbol3.Parameters[0].GetHashCode());
}
Assert.Equal(symbol2, symbol4);
TypeSymbol underlying = type;
if (op == UnaryOperatorKind.BitwiseComplement ||
op == UnaryOperatorKind.PrefixDecrement || op == UnaryOperatorKind.PrefixIncrement ||
op == UnaryOperatorKind.PostfixDecrement || op == UnaryOperatorKind.PostfixIncrement)
{
underlying = type.EnumUnderlyingTypeOrSelf();
}
UnaryOperatorKind result = OverloadResolution.UnopEasyOut.OpKind(op, underlying);
UnaryOperatorSignature signature;
if (result == UnaryOperatorKind.Error)
{
if (type.IsDynamic())
{
signature = new UnaryOperatorSignature(op | UnaryOperatorKind.Dynamic, type, type);
}
else if (type.IsPointerType() &&
(op == UnaryOperatorKind.PrefixDecrement || op == UnaryOperatorKind.PrefixIncrement ||
op == UnaryOperatorKind.PostfixDecrement || op == UnaryOperatorKind.PostfixIncrement))
{
signature = new UnaryOperatorSignature(op | UnaryOperatorKind.Pointer, type, type);
}
else
{
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
}
else
{
signature = compilation.builtInOperators.GetSignature(result);
if ((object)underlying != (object)type)
{
Assert.Equal(underlying, signature.OperandType);
Assert.Equal(underlying, signature.ReturnType);
signature = new UnaryOperatorSignature(signature.Kind, type, type);
}
}
Assert.NotNull(symbol1);
string containerName = signature.OperandType.ToTestDisplayString();
string returnName = signature.ReturnType.ToTestDisplayString();
if (op == UnaryOperatorKind.LogicalNegation && type.IsEnumType())
{
containerName = type.ToTestDisplayString();
returnName = containerName;
}
Assert.Equal(String.Format("{2} {0}.{1}({0} value)",
containerName,
OperatorFacts.UnaryOperatorNameFromOperatorKind(op),
returnName),
symbol1.ToTestDisplayString());
Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind);
Assert.True(symbol1.IsImplicitlyDeclared);
bool expectChecked = false;
switch (op)
{
case UnaryOperatorKind.UnaryMinus:
expectChecked = (type.IsDynamic() || symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType());
break;
case UnaryOperatorKind.PrefixDecrement:
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.PostfixIncrement:
expectChecked = (type.IsDynamic() || type.IsPointerType() ||
symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType() ||
symbol1.ContainingType.SpecialType == SpecialType.System_Char);
break;
default:
expectChecked = type.IsDynamic();
break;
}
Assert.Equal(expectChecked, symbol1.IsCheckedBuiltin);
Assert.False(symbol1.IsGenericMethod);
Assert.False(symbol1.IsExtensionMethod);
Assert.False(symbol1.IsExtern);
Assert.False(symbol1.CanBeReferencedByName);
Assert.Null(symbol1.GetSymbol().DeclaringCompilation);
Assert.Equal(symbol1.Name, symbol1.MetadataName);
Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters[0].Type);
Assert.Equal(0, symbol1.Locations.Length);
Assert.Null(symbol1.GetDocumentationCommentId());
Assert.Equal("", symbol1.GetDocumentationCommentXml());
Assert.True(symbol1.GetSymbol().HasSpecialName);
Assert.True(symbol1.IsStatic);
Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility);
Assert.False(symbol1.HidesBaseMethodsByName);
Assert.False(symbol1.IsOverride);
Assert.False(symbol1.IsVirtual);
Assert.False(symbol1.IsAbstract);
Assert.False(symbol1.IsSealed);
Assert.Equal(1, symbol1.GetSymbol().ParameterCount);
Assert.Equal(0, symbol1.Parameters[0].Ordinal);
var otherSymbol = (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol;
Assert.Equal(symbol1, otherSymbol);
if (type.IsValueType && !type.IsPointerType())
{
Assert.Equal(symbol1, symbol2);
return;
}
Assert.Null(symbol2);
}
[Fact]
[WorkItem(39975, "https://github.com/dotnet/roslyn/issues/39975")]
public void CheckedUnaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(int x)
{
var z1 = -x;
var z2 = --x;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select ((ExpressionSyntax)(node as PrefixUnaryExpressionSyntax)) ?? node as PostfixUnaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/mono/mono/issues/10917")]
public void BinaryIntrinsicSymbols1()
{
BinaryOperatorKind[] operators =
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.Equal,
BinaryOperatorKind.NotEqual,
BinaryOperatorKind.LessThanOrEqual,
BinaryOperatorKind.GreaterThanOrEqual,
BinaryOperatorKind.LessThan,
BinaryOperatorKind.GreaterThan,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Or,
BinaryOperatorKind.And,
BinaryOperatorKind.LogicalOr,
BinaryOperatorKind.LogicalAnd
};
string[] opTokens = {
"+",
"-",
"*",
"/",
"%",
"==",
"!=",
"<=",
">=",
"<",
">",
"<<",
">>",
"^",
"|",
"&",
"||",
"&&"};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"System.Delegate",
"System.Action",
"System.AppDomainInitializer",
"System.ValueType",
"TestStructure",
"Module1",
"dynamic",
"byte*",
"sbyte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"struct TestStructure\n" +
"{}\n" +
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
foreach (var arg2 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{2}({0} x1, {1} y1, System.Nullable<{0}> x2, System.Nullable<{1}> y2)\n" +
"{{\n", arg1, arg2, n);
for (int k = 0; k < opTokens.Length; k++)
{
builder.AppendFormat(
" var z{0}_1 = x1 {1} y1;\n" +
" var z{0}_2 = x2 {1} y2;\n" +
" var z{0}_3 = x2 {1} y1;\n" +
" var z{0}_4 = x1 {1} y2;\n" +
" if (x1 {1} y1) {{}}\n" +
" if (x2 {1} y2) {{}}\n" +
" if (x2 {1} y1) {{}}\n" +
" if (x1 {1} y2) {{}}\n",
k, opTokens[k]);
}
builder.Append(
"}\n");
}
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45Extended, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
TypeSymbol[] types = new TypeSymbol[typeNames.Length];
for (int i = 0; i < typeNames.Length - 3; i++)
{
types[i] = compilation.GetTypeByMetadataName(typeNames[i]);
}
Assert.Null(types[types.Length - 3]);
types[types.Length - 3] = compilation.DynamicType;
Assert.Null(types[types.Length - 2]);
types[types.Length - 2] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
Assert.Null(types[types.Length - 1]);
types[types.Length - 1] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_SByte));
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as BinaryExpressionSyntax)).
Where(node => (object)node != null).ToArray();
n = 0;
foreach (var leftType in types)
{
foreach (var rightType in types)
{
foreach (var op in operators)
{
TestBinaryIntrinsicSymbol(
op,
leftType,
rightType,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3],
nodes[n + 4],
nodes[n + 5],
nodes[n + 6],
nodes[n + 7]);
n += 8;
}
}
}
Assert.Equal(n, nodes.Length);
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(39975, "https://github.com/dotnet/roslyn/issues/39975")]
public void BinaryIntrinsicSymbols2()
{
BinaryOperatorKind[] operators =
{
BinaryOperatorKind.Addition,
BinaryOperatorKind.Subtraction,
BinaryOperatorKind.Multiplication,
BinaryOperatorKind.Division,
BinaryOperatorKind.Remainder,
BinaryOperatorKind.LeftShift,
BinaryOperatorKind.RightShift,
BinaryOperatorKind.Xor,
BinaryOperatorKind.Or,
BinaryOperatorKind.And
};
string[] opTokens = {
"+=",
"-=",
"*=",
"/=",
"%=",
"<<=",
">>=",
"^=",
"|=",
"&="};
string[] typeNames =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid",
"System.Delegate",
"System.Action",
"System.AppDomainInitializer",
"System.ValueType",
"TestStructure",
"Module1",
"dynamic",
"byte*",
"sbyte*"
};
var builder = new System.Text.StringBuilder();
int n = 0;
builder.Append(
"struct TestStructure\n" +
"{}\n" +
"class Module1\n" +
"{\n");
foreach (var arg1 in typeNames)
{
foreach (var arg2 in typeNames)
{
n += 1;
builder.AppendFormat(
"void Test{2}({0} x1, {1} y1, System.Nullable<{0}> x2, System.Nullable<{1}> y2)\n" +
"{{\n", arg1, arg2, n);
for (int k = 0; k < opTokens.Length; k++)
{
builder.AppendFormat(
" x1 {1} y1;\n" +
" x2 {1} y2;\n" +
" x2 {1} y1;\n" +
" x1 {1} y2;\n" +
" if (x1 {1} y1) {{}}\n" +
" if (x2 {1} y2) {{}}\n" +
" if (x2 {1} y1) {{}}\n" +
" if (x1 {1} y2) {{}}\n",
k, opTokens[k]);
}
builder.Append(
"}\n");
}
}
builder.Append(
"}\n");
var source = builder.ToString();
var compilation = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40Extended, options: TestOptions.ReleaseDll.WithOverflowChecks(true));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
TypeSymbol[] types = new TypeSymbol[typeNames.Length];
for (int i = 0; i < typeNames.Length - 3; i++)
{
types[i] = compilation.GetTypeByMetadataName(typeNames[i]);
}
Assert.Null(types[types.Length - 3]);
types[types.Length - 3] = compilation.DynamicType;
Assert.Null(types[types.Length - 2]);
types[types.Length - 2] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Byte));
Assert.Null(types[types.Length - 1]);
types[types.Length - 1] = compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_SByte));
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as AssignmentExpressionSyntax)).
Where(node => (object)node != null).ToArray();
n = 0;
foreach (var leftType in types)
{
foreach (var rightType in types)
{
foreach (var op in operators)
{
TestBinaryIntrinsicSymbol(
op,
leftType,
rightType,
compilation,
semanticModel,
nodes[n],
nodes[n + 1],
nodes[n + 2],
nodes[n + 3],
nodes[n + 4],
nodes[n + 5],
nodes[n + 6],
nodes[n + 7]);
n += 8;
}
}
}
Assert.Equal(n, nodes.Length);
}
private void TestBinaryIntrinsicSymbol(
BinaryOperatorKind op,
TypeSymbol leftType,
TypeSymbol rightType,
CSharpCompilation compilation,
SemanticModel semanticModel,
ExpressionSyntax node1,
ExpressionSyntax node2,
ExpressionSyntax node3,
ExpressionSyntax node4,
ExpressionSyntax node5,
ExpressionSyntax node6,
ExpressionSyntax node7,
ExpressionSyntax node8
)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if (info1.Symbol == null)
{
if (info1.CandidateSymbols.Length == 0)
{
if (leftType.IsDynamic() || rightType.IsDynamic())
{
Assert.True(CandidateReason.LateBound == info1.CandidateReason || CandidateReason.None == info1.CandidateReason);
}
else
{
Assert.Equal(CandidateReason.None, info1.CandidateReason);
}
}
else
{
Assert.Equal(CandidateReason.OverloadResolutionFailure, info1.CandidateReason);
foreach (MethodSymbol s in info1.CandidateSymbols)
{
Assert.Equal(MethodKind.UserDefinedOperator, s.MethodKind);
}
}
}
else
{
Assert.Equal(leftType.IsDynamic() || rightType.IsDynamic() ? CandidateReason.LateBound : CandidateReason.None, info1.CandidateReason);
Assert.Equal(0, info1.CandidateSymbols.Length);
}
var symbol1 = (IMethodSymbol)info1.Symbol;
var symbol2 = semanticModel.GetSymbolInfo(node2).Symbol;
var symbol3 = semanticModel.GetSymbolInfo(node3).Symbol;
var symbol4 = semanticModel.GetSymbolInfo(node4).Symbol;
var symbol5 = (IMethodSymbol)semanticModel.GetSymbolInfo(node5).Symbol;
var symbol6 = semanticModel.GetSymbolInfo(node6).Symbol;
var symbol7 = semanticModel.GetSymbolInfo(node7).Symbol;
var symbol8 = semanticModel.GetSymbolInfo(node8).Symbol;
Assert.Equal(symbol1, symbol5);
Assert.Equal(symbol2, symbol6);
Assert.Equal(symbol3, symbol7);
Assert.Equal(symbol4, symbol8);
if ((object)symbol1 != null && symbol1.IsImplicitlyDeclared)
{
Assert.NotSame(symbol1, symbol5);
Assert.Equal(symbol1.GetHashCode(), symbol5.GetHashCode());
for (int i = 0; i < 2; i++)
{
Assert.Equal(symbol1.Parameters[i], symbol5.Parameters[i]);
Assert.Equal(symbol1.Parameters[i].GetHashCode(), symbol5.Parameters[i].GetHashCode());
}
Assert.NotEqual(symbol1.Parameters[0], symbol5.Parameters[1]);
}
switch (op)
{
case BinaryOperatorKind.LogicalAnd:
case BinaryOperatorKind.LogicalOr:
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
BinaryOperatorKind result = OverloadResolution.BinopEasyOut.OpKind(op, leftType, rightType);
BinaryOperatorSignature signature;
bool isDynamic = (leftType.IsDynamic() || rightType.IsDynamic());
if (result == BinaryOperatorKind.Error)
{
if (leftType.IsDynamic() && !rightType.IsPointerType() && !rightType.IsRestrictedType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Dynamic, leftType, rightType, leftType);
}
else if (rightType.IsDynamic() && !leftType.IsPointerType() && !leftType.IsRestrictedType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Dynamic, leftType, rightType, rightType);
}
else if ((op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) &&
leftType.IsReferenceType && rightType.IsReferenceType &&
(TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2) || compilation.Conversions.ClassifyConversionFromType(leftType, rightType, ref useSiteDiagnostics).IsReference))
{
if (leftType.IsDelegateType() && rightType.IsDelegateType())
{
Assert.Equal(leftType, rightType);
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate,
leftType, // TODO: this feels like a spec violation
leftType, // TODO: this feels like a spec violation
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else if (leftType.SpecialType == SpecialType.System_Delegate && rightType.SpecialType == SpecialType.System_Delegate)
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate,
compilation.GetSpecialType(SpecialType.System_Delegate), compilation.GetSpecialType(SpecialType.System_Delegate),
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Object, compilation.ObjectType, compilation.ObjectType,
compilation.GetSpecialType(SpecialType.System_Boolean));
}
}
else if (op == BinaryOperatorKind.Addition &&
((leftType.IsStringType() && !rightType.IsPointerType()) || (!leftType.IsPointerType() && rightType.IsStringType())))
{
Assert.False(leftType.IsStringType() && rightType.IsStringType());
if (leftType.IsStringType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, leftType, compilation.ObjectType, leftType);
}
else
{
Assert.True(rightType.IsStringType());
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, compilation.ObjectType, rightType, rightType);
}
}
else if (op == BinaryOperatorKind.Addition &&
(((leftType.IsIntegralType() || leftType.IsCharType()) && rightType.IsPointerType()) ||
(leftType.IsPointerType() && (rightType.IsIntegralType() || rightType.IsCharType()))))
{
if (leftType.IsPointerType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, leftType, symbol1.Parameters[1].Type.GetSymbol(), leftType);
Assert.True(symbol1.Parameters[1].Type.GetSymbol().IsIntegralType());
}
else
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, symbol1.Parameters[0].Type.GetSymbol(), rightType, rightType);
Assert.True(symbol1.Parameters[0].Type.GetSymbol().IsIntegralType());
}
}
else if (op == BinaryOperatorKind.Subtraction &&
(leftType.IsPointerType() && (rightType.IsIntegralType() || rightType.IsCharType())))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.String, leftType, symbol1.Parameters[1].Type.GetSymbol(), leftType);
Assert.True(symbol1.Parameters[1].Type.GetSymbol().IsIntegralType());
}
else if (op == BinaryOperatorKind.Subtraction && leftType.IsPointerType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer, leftType, rightType, compilation.GetSpecialType(SpecialType.System_Int64));
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
leftType.IsEnumType() && (rightType.IsIntegralType() || rightType.IsCharType()) &&
(result = OverloadResolution.BinopEasyOut.OpKind(op, leftType.EnumUnderlyingTypeOrSelf(), rightType)) != BinaryOperatorKind.Error &&
TypeSymbol.Equals((signature = compilation.builtInOperators.GetSignature(result)).RightType, leftType.EnumUnderlyingTypeOrSelf(), TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(signature.Kind | BinaryOperatorKind.EnumAndUnderlying, leftType, signature.RightType, leftType);
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
rightType.IsEnumType() && (leftType.IsIntegralType() || leftType.IsCharType()) &&
(result = OverloadResolution.BinopEasyOut.OpKind(op, leftType, rightType.EnumUnderlyingTypeOrSelf())) != BinaryOperatorKind.Error &&
TypeSymbol.Equals((signature = compilation.builtInOperators.GetSignature(result)).LeftType, rightType.EnumUnderlyingTypeOrSelf(), TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(signature.Kind | BinaryOperatorKind.EnumAndUnderlying, signature.LeftType, rightType, rightType);
}
else if (op == BinaryOperatorKind.Subtraction &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, leftType.EnumUnderlyingTypeOrSelf());
}
else if ((op == BinaryOperatorKind.Equal ||
op == BinaryOperatorKind.NotEqual ||
op == BinaryOperatorKind.LessThan ||
op == BinaryOperatorKind.LessThanOrEqual ||
op == BinaryOperatorKind.GreaterThan ||
op == BinaryOperatorKind.GreaterThanOrEqual) &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, compilation.GetSpecialType(SpecialType.System_Boolean));
}
else if ((op == BinaryOperatorKind.Xor ||
op == BinaryOperatorKind.And ||
op == BinaryOperatorKind.Or) &&
leftType.IsEnumType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Enum, leftType, rightType, leftType);
}
else if ((op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction) &&
leftType.IsDelegateType() && TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2))
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Delegate, leftType, leftType, leftType);
}
else if ((op == BinaryOperatorKind.Equal ||
op == BinaryOperatorKind.NotEqual ||
op == BinaryOperatorKind.LessThan ||
op == BinaryOperatorKind.LessThanOrEqual ||
op == BinaryOperatorKind.GreaterThan ||
op == BinaryOperatorKind.GreaterThanOrEqual) &&
leftType.IsPointerType() && rightType.IsPointerType())
{
signature = new BinaryOperatorSignature(op | BinaryOperatorKind.Pointer,
compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Void)),
compilation.CreatePointerTypeSymbol(compilation.GetSpecialType(SpecialType.System_Void)),
compilation.GetSpecialType(SpecialType.System_Boolean));
}
else
{
if ((object)symbol1 != null)
{
Assert.False(symbol1.IsImplicitlyDeclared);
Assert.Equal(MethodKind.UserDefinedOperator, symbol1.MethodKind);
if (leftType.IsValueType && !leftType.IsPointerType())
{
if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Same(symbol1, symbol2);
Assert.Same(symbol1, symbol3);
Assert.Same(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
Assert.Same(symbol1, symbol3);
Assert.Null(symbol4);
return;
}
}
else if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Same(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
}
Assert.Null(symbol1);
Assert.Null(symbol2);
if (!rightType.IsDynamic())
{
Assert.Null(symbol3);
}
if (!leftType.IsDynamic())
{
Assert.Null(symbol4);
}
return;
}
}
else if ((op == BinaryOperatorKind.Equal || op == BinaryOperatorKind.NotEqual) &&
!TypeSymbol.Equals(leftType, rightType, TypeCompareKind.ConsiderEverything2) &&
(!leftType.IsValueType || !rightType.IsValueType ||
leftType.SpecialType == SpecialType.System_Boolean || rightType.SpecialType == SpecialType.System_Boolean ||
(leftType.SpecialType == SpecialType.System_Decimal && (rightType.SpecialType == SpecialType.System_Double || rightType.SpecialType == SpecialType.System_Single)) ||
(rightType.SpecialType == SpecialType.System_Decimal && (leftType.SpecialType == SpecialType.System_Double || leftType.SpecialType == SpecialType.System_Single))) &&
(!leftType.IsReferenceType || !rightType.IsReferenceType ||
!compilation.Conversions.ClassifyConversionFromType(leftType, rightType, ref useSiteDiagnostics).IsReference))
{
Assert.Null(symbol1);
Assert.Null(symbol2);
Assert.Null(symbol3);
Assert.Null(symbol4);
return;
}
else
{
signature = compilation.builtInOperators.GetSignature(result);
}
Assert.NotNull(symbol1);
string containerName = signature.LeftType.ToTestDisplayString();
string leftName = containerName;
string rightName = signature.RightType.ToTestDisplayString();
string returnName = signature.ReturnType.ToTestDisplayString();
if (isDynamic)
{
containerName = compilation.DynamicType.ToTestDisplayString();
}
else if (op == BinaryOperatorKind.Addition || op == BinaryOperatorKind.Subtraction)
{
if (signature.LeftType.IsObjectType() && signature.RightType.IsStringType())
{
containerName = rightName;
}
else if ((leftType.IsEnumType() || leftType.IsPointerType()) && (rightType.IsIntegralType() || rightType.IsCharType()))
{
containerName = leftType.ToTestDisplayString();
leftName = containerName;
returnName = containerName;
}
else if ((rightType.IsEnumType() || rightType.IsPointerType()) && (leftType.IsIntegralType() || leftType.IsCharType()))
{
containerName = rightType.ToTestDisplayString();
rightName = containerName;
returnName = containerName;
}
}
Assert.Equal(isDynamic, signature.ReturnType.IsDynamic());
string expectedSymbol = String.Format("{4} {0}.{2}({1} left, {3} right)",
containerName,
leftName,
OperatorFacts.BinaryOperatorNameFromOperatorKind(op),
rightName,
returnName);
string actualSymbol = symbol1.ToTestDisplayString();
Assert.Equal(expectedSymbol, actualSymbol);
Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind);
Assert.True(symbol1.IsImplicitlyDeclared);
bool isChecked;
switch (op)
{
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Division:
isChecked = isDynamic || symbol1.ContainingSymbol.Kind == SymbolKind.PointerType || symbol1.ContainingType.EnumUnderlyingTypeOrSelf().SpecialType.IsIntegralType();
break;
default:
isChecked = isDynamic;
break;
}
Assert.Equal(isChecked, symbol1.IsCheckedBuiltin);
Assert.False(symbol1.IsGenericMethod);
Assert.False(symbol1.IsExtensionMethod);
Assert.False(symbol1.IsExtern);
Assert.False(symbol1.CanBeReferencedByName);
Assert.Null(symbol1.GetSymbol().DeclaringCompilation);
Assert.Equal(symbol1.Name, symbol1.MetadataName);
Assert.True(SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[0].Type) ||
SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[1].Type));
int match = 0;
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.ReturnType))
{
match++;
}
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[0].Type))
{
match++;
}
if (SymbolEqualityComparer.ConsiderEverything.Equals(symbol1.ContainingSymbol, symbol1.Parameters[1].Type))
{
match++;
}
Assert.True(match >= 2);
Assert.Equal(0, symbol1.Locations.Length);
Assert.Null(symbol1.GetDocumentationCommentId());
Assert.Equal("", symbol1.GetDocumentationCommentXml());
Assert.True(symbol1.GetSymbol().HasSpecialName);
Assert.True(symbol1.IsStatic);
Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility);
Assert.False(symbol1.HidesBaseMethodsByName);
Assert.False(symbol1.IsOverride);
Assert.False(symbol1.IsVirtual);
Assert.False(symbol1.IsAbstract);
Assert.False(symbol1.IsSealed);
Assert.Equal(2, symbol1.Parameters.Length);
Assert.Equal(0, symbol1.Parameters[0].Ordinal);
Assert.Equal(1, symbol1.Parameters[1].Ordinal);
var otherSymbol = (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol;
Assert.Equal(symbol1, otherSymbol);
if (leftType.IsValueType && !leftType.IsPointerType())
{
if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Equal(symbol1, symbol2);
Assert.Equal(symbol1, symbol3);
Assert.Equal(symbol1, symbol4);
return;
}
else
{
Assert.Null(symbol2);
if (rightType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol3);
}
else
{
Assert.Equal(rightType.IsPointerType() ? null : symbol1, symbol3);
}
Assert.Null(symbol4);
return;
}
}
else if (rightType.IsValueType && !rightType.IsPointerType())
{
Assert.Null(symbol2);
Assert.Null(symbol3);
if (leftType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol4);
}
else
{
Assert.Equal(leftType.IsPointerType() ? null : symbol1, symbol4);
}
return;
}
Assert.Null(symbol2);
if (rightType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol3);
}
else
{
Assert.Null(symbol3);
}
if (leftType.IsDynamic())
{
Assert.NotEqual(symbol1, symbol4);
}
else
{
Assert.Null(symbol4);
}
}
[Fact()]
public void BinaryIntrinsicSymbols3()
{
var source =
@"
class Module1
{
void Test(object x)
{
var z1 = x as string;
var z2 = x is string;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
foreach (var node1 in nodes)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(node1);
Assert.Null(info1.Symbol);
Assert.Equal(0, info1.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, info1.CandidateReason);
}
}
[Fact()]
public void CheckedBinaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(int x, int y)
{
var z1 = x + y;
x += y;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = tree.GetRoot().DescendantNodes().Where(node => node is BinaryExpressionSyntax || node is AssignmentExpressionSyntax).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[Fact()]
public void DynamicBinaryIntrinsicSymbols()
{
var source =
@"
class Module1
{
void Test(dynamic x)
{
var z1 = x == null;
var z2 = null == x;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOverflowChecks(false));
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(2, nodes.Length);
var symbols1 = (from node1 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node1).Symbol).ToArray();
foreach (var symbol1 in symbols1)
{
Assert.False(symbol1.IsCheckedBuiltin);
Assert.True(((ITypeSymbol)symbol1.ContainingSymbol).IsDynamic());
Assert.Null(symbol1.ContainingType);
}
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(true));
semanticModel = compilation.GetSemanticModel(tree);
var symbols2 = (from node2 in nodes select (IMethodSymbol)semanticModel.GetSymbolInfo(node2).Symbol).ToArray();
foreach (var symbol2 in symbols2)
{
Assert.True(symbol2.IsCheckedBuiltin);
Assert.True(((ITypeSymbol)symbol2.ContainingSymbol).IsDynamic());
Assert.Null(symbol2.ContainingType);
}
for (int i = 0; i < symbols1.Length; i++)
{
Assert.NotEqual(symbols1[i], symbols2[i]);
}
}
[Fact(), WorkItem(721565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/721565")]
public void Bug721565()
{
var source =
@"
class Module1
{
void Test(TestStr? x, int? y, TestStr? x1, int? y1)
{
var z1 = (x == null);
var z2 = (x != null);
var z3 = (null == x);
var z4 = (null != x);
var z5 = (y == null);
var z6 = (y != null);
var z7 = (null == y);
var z8 = (null != y);
var z9 = (y == y1);
var z10 = (y != y1);
var z11 = (x == x1);
var z12 = (x != x1);
}
}
struct TestStr
{}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (17,20): error CS0019: Operator '==' cannot be applied to operands of type 'TestStr?' and 'TestStr?'
// var z11 = (x == x1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == x1").WithArguments("==", "TestStr?", "TestStr?"),
// (18,20): error CS0019: Operator '!=' cannot be applied to operands of type 'TestStr?' and 'TestStr?'
// var z12 = (x != x1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x != x1").WithArguments("!=", "TestStr?", "TestStr?")
);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select node as BinaryExpressionSyntax).
Where(node => (object)node != null).ToArray();
Assert.Equal(12, nodes.Length);
for (int i = 0; i < 12; i++)
{
SymbolInfo info1 = semanticModel.GetSymbolInfo(nodes[i]);
switch (i)
{
case 0:
case 2:
case 4:
case 6:
Assert.Equal("System.Boolean System.Object.op_Equality(System.Object left, System.Object right)", info1.Symbol.ToTestDisplayString());
break;
case 1:
case 3:
case 5:
case 7:
Assert.Equal("System.Boolean System.Object.op_Inequality(System.Object left, System.Object right)", info1.Symbol.ToTestDisplayString());
break;
case 8:
Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", info1.Symbol.ToTestDisplayString());
break;
case 9:
Assert.Equal("System.Boolean System.Int32.op_Inequality(System.Int32 left, System.Int32 right)", info1.Symbol.ToTestDisplayString());
break;
case 10:
case 11:
Assert.Null(info1.Symbol);
break;
default:
throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(i);
}
}
}
[Fact]
public void IntrinsicBinaryOperatorSignature_EqualsAndGetHashCode()
{
var source =
@"class C
{
static object F(int i)
{
return i += 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
var methodBody = methodDecl.Body;
var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
var binder = model.GetEnclosingBinder(methodBody.SpanStart);
var diagnostics = DiagnosticBag.GetInstance();
var block = binder.BindEmbeddedBlock(methodBody, diagnostics);
diagnostics.Free();
// Rewriter should use Equals.
var rewriter = new EmptyRewriter();
var node = rewriter.Visit(block);
Assert.Same(node, block);
var visitor = new FindCompoundAssignmentWalker();
visitor.Visit(block);
var op = visitor.FirstNode.Operator;
Assert.Null(op.Method);
// Equals and GetHashCode should support null Method.
Assert.Equal(op, new BinaryOperatorSignature(op.Kind, op.LeftType, op.RightType, op.ReturnType, op.Method, constrainedToTypeOpt: null));
op.GetHashCode();
}
[Fact]
public void StrictEnumSubtraction()
{
var source1 =
@"public enum Color { Red, Blue, Green }
public static class Program
{
public static void M<T>(T t) {}
public static void Main(string[] args)
{
M(1 - Color.Red);
}
}";
CreateCompilation(source1, options: TestOptions.ReleaseDll).VerifyDiagnostics(
);
CreateCompilation(source1, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(
// (7,11): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'Color'
// M(1 - Color.Red);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - Color.Red").WithArguments("-", "int", "Color").WithLocation(7, 11)
);
}
/// <summary>
/// Operators && and || are supported when operators
/// & and | are defined on the same type or a derived type
/// from operators true and false only. This matches Dev12.
/// </summary>
[WorkItem(1079034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079034")]
[Fact]
public void UserDefinedShortCircuitingOperators_TrueAndFalseOnBaseType()
{
var source =
@"class A<T>
{
public static bool operator true(A<T> o) { return true; }
public static bool operator false(A<T> o) { return false; }
}
class B : A<object>
{
public static B operator &(B x, B y) { return x; }
}
class C : B
{
public static C operator |(C x, C y) { return x; }
}
class P
{
static void M(C x, C y)
{
if (x && y)
{
}
if (x || y)
{
}
}
}";
var verifier = CompileAndVerify(source);
verifier.Compilation.VerifyDiagnostics();
verifier.VerifyIL("P.M",
@"
{
// Code size 53 (0x35)
.maxstack 2
.locals init (B V_0,
C V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call ""bool A<object>.op_False(A<object>)""
IL_0008: brtrue.s IL_0013
IL_000a: ldloc.0
IL_000b: ldarg.1
IL_000c: call ""B B.op_BitwiseAnd(B, B)""
IL_0011: br.s IL_0014
IL_0013: ldloc.0
IL_0014: call ""bool A<object>.op_True(A<object>)""
IL_0019: pop
IL_001a: ldarg.0
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: call ""bool A<object>.op_True(A<object>)""
IL_0022: brtrue.s IL_002d
IL_0024: ldloc.1
IL_0025: ldarg.1
IL_0026: call ""C C.op_BitwiseOr(C, C)""
IL_002b: br.s IL_002e
IL_002d: ldloc.1
IL_002e: call ""bool A<object>.op_True(A<object>)""
IL_0033: pop
IL_0034: ret
}");
}
/// <summary>
/// Operators && and || are supported when operators
/// & and | are defined on the same type or a derived type
/// from operators true and false only. This matches Dev12.
/// </summary>
[Fact]
public void UserDefinedShortCircuitingOperators_TrueAndFalseOnDerivedType()
{
var source =
@"class A<T>
{
public static A<T> operator |(A<T> x, A<T> y) { return x; }
}
class B : A<object>
{
public static B operator &(B x, B y) { return x; }
}
class C : B
{
public static bool operator true(C o) { return true; }
public static bool operator false(C o) { return false; }
}
class P
{
static void M(C x, C y)
{
if (x && y)
{
}
if (x || y)
{
}
}
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (18,13): error CS0218: In order for 'B.operator &(B, B)' to be applicable as a short circuit operator, its declaring type 'B' must define operator true and operator false
// if (x && y)
Diagnostic(ErrorCode.ERR_MustHaveOpTF, "x && y").WithArguments("B.operator &(B, B)", "B").WithLocation(18, 13),
// (21,13): error CS0218: In order for 'A<object>.operator |(A<object>, A<object>)' to be applicable as a short circuit operator, its declaring type 'A<object>' must define operator true and operator false
// if (x || y)
Diagnostic(ErrorCode.ERR_MustHaveOpTF, "x || y").WithArguments("A<object>.operator |(A<object>, A<object>)", "A<object>").WithLocation(21, 13));
}
private sealed class EmptyRewriter : BoundTreeRewriter
{
protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node)
{
throw new NotImplementedException();
}
}
private sealed class FindCompoundAssignmentWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
internal BoundCompoundAssignmentOperator FirstNode;
public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
if (FirstNode == null)
{
FirstNode = node;
}
return base.VisitCompoundAssignmentOperator(node);
}
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_0()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
const int y = 0;
x -= y;
}
}
enum E : short { }
";
CompileAndVerify(source: source);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_1()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
x -= new Test();
}
}
enum E : short { }
class Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_2()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
var y = new Test() - x;
}
}
enum E : short { }
class Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_3()
{
string source = @"
class Program
{
static void Main()
{
E x = 0;
const int y = 0;
Print(x - y);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}
enum E : short { }";
CompileAndVerify(source: source, expectedOutput: "System.Int16");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_4()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
x -= new Test?(new Test());
}
}
enum E : short { }
struct Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_5()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
var y = new Test?(new Test());
var z = y - x;
}
}
enum E : short { }
struct Test
{
public static implicit operator short (Test x)
{
System.Console.WriteLine(""implicit operator short"");
return 0;
}
public static implicit operator E(Test x)
{
System.Console.WriteLine(""implicit operator E"");
return 0;
}
}";
CompileAndVerify(source: source, expectedOutput: "implicit operator E");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_6()
{
string source = @"
class Program
{
static void Main()
{
E? x = 0;
const int y = 0;
Print(x - y);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}
enum E : short { }";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Int16]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_7()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
Base64FormattingOptions? xn0 = Base64FormattingOptions.None;
Print(xn0 - 0);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Base64FormattingOptions]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_8()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
Base64FormattingOptions? xn0 = Base64FormattingOptions.None;
Print(0 - xn0);
}
static void Print<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
CompileAndVerify(source: source, expectedOutput: "System.Nullable`1[System.Int32]");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_9()
{
string source = @"
using System;
enum MyEnum1 : short
{
A, B
}
enum MyEnum2
{
A, B
}
class Program
{
static void M<T>(T t)
{
Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
MyEnum1 m1 = (long)0;
M((short)0 - m1);
M((int)0 - m1);
M((long)0 - m1);
MyEnum2 m2 = 0;
M((short)0 - m2);
M((int)0 - m2);
M((long)0 - m2);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Int16
System.Int16
System.Int16
System.Int32
System.Int32
System.Int32");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_10()
{
string source = @"
enum TestEnum : short
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
byte a = 1;
short b = 1;
byte e = 0;
short f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test2()
{
TestEnum? x = 0;
byte a = 1;
short b = 1;
byte e = 0;
short f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test3()
{
TestEnum x = 0;
byte? a = 1;
short? b = 1;
byte? e = 0;
short? f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test4()
{
TestEnum? x = 0;
byte? a = 1;
short? b = 1;
byte? e = 0;
short? f = 0;
Print(x - a);
Print(x - b);
Print(x - e);
Print(x - f);
Print(a - x);
Print(b - x);
Print(e - x);
Print(f - x);
}
static void Test5()
{
TestEnum x = 0;
const byte a = 1;
const short b = 1;
const int c = 1;
const byte e = 0;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - a);
Print(x - b);
Print(x - c);
Print(x - e);
Print(x - f);
Print(x - g);
Print(x - h);
Print(a - x);
Print(b - x);
Print(c - x);
Print(e - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const byte a = 1;
const short b = 1;
const int c = 1;
const byte e = 0;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - a);
Print(x - b);
Print(x - c);
Print(x - e);
Print(x - f);
Print(x - g);
Print(x - h);
Print(a - x);
Print(b - x);
Print(c - x);
Print(e - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (byte)1);
Print(x - (short)1);
Print(x - (int)1);
Print(x - (byte)0);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((byte)1 - x);
Print((short)1 - x);
Print((int)1 - x);
Print((byte)0 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (byte)1);
Print(x - (short)1);
Print(x - (int)1);
Print(x - (byte)0);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((byte)1 - x);
Print((short)1 - x);
Print((int)1 - x);
Print((byte)0 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
TestEnum
System.Int16
TestEnum
System.Int16
System.Int16
TestEnum
TestEnum
TestEnum
System.Int16
System.Int16
System.Int16
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
TestEnum
TestEnum
TestEnum
System.Int16
TestEnum
System.Int16
System.Int16
TestEnum
TestEnum
TestEnum
System.Int16
System.Int16
System.Int16
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
TestEnum
System.Int16
TestEnum
System.Int16
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int16]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_11()
{
string source = @"
enum TestEnum : short
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
}
static void Test1()
{
TestEnum x = 0;
int c = 1;
long d = 1;
int g = 0;
long h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
int c = 1;
long d = 1;
int g = 0;
long h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
int? c = 1;
long? d = 1;
int? g = 0;
long? h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
int? c = 1;
long? d = 1;
int? g = 0;
long? h = 0;
Print(x - c);
Print(x - d);
Print(x - g);
Print(x - h);
Print(c - x);
Print(d - x);
Print(g - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test6()
{
TestEnum? x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (26,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum", "int").WithLocation(26, 15),
// (27,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(27, 15),
// (28,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum", "int").WithLocation(28, 15),
// (29,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long").WithLocation(29, 15),
// (30,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int", "TestEnum").WithLocation(30, 15),
// (31,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(31, 15),
// (32,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int", "TestEnum").WithLocation(32, 15),
// (33,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum").WithLocation(33, 15),
// (44,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum?", "int").WithLocation(44, 15),
// (45,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(45, 15),
// (46,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum?", "int").WithLocation(46, 15),
// (47,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long").WithLocation(47, 15),
// (48,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum?'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int", "TestEnum?").WithLocation(48, 15),
// (49,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(49, 15),
// (50,15): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'TestEnum?'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int", "TestEnum?").WithLocation(50, 15),
// (51,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum?").WithLocation(51, 15),
// (62,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int?'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum", "int?").WithLocation(62, 15),
// (63,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long?").WithLocation(63, 15),
// (64,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'int?'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum", "int?").WithLocation(64, 15),
// (65,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long?").WithLocation(65, 15),
// (66,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int?", "TestEnum").WithLocation(66, 15),
// (67,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum").WithLocation(67, 15),
// (68,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int?", "TestEnum").WithLocation(68, 15),
// (69,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum").WithLocation(69, 15),
// (80,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int?'
// Print(x - c);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - c").WithArguments("-", "TestEnum?", "int?").WithLocation(80, 15),
// (81,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long?").WithLocation(81, 15),
// (82,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'int?'
// Print(x - g);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - g").WithArguments("-", "TestEnum?", "int?").WithLocation(82, 15),
// (83,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long?").WithLocation(83, 15),
// (84,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum?'
// Print(c - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c - x").WithArguments("-", "int?", "TestEnum?").WithLocation(84, 15),
// (85,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum?").WithLocation(85, 15),
// (86,15): error CS0019: Operator '-' cannot be applied to operands of type 'int?' and 'TestEnum?'
// Print(g - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "g - x").WithArguments("-", "int?", "TestEnum?").WithLocation(86, 15),
// (87,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum?").WithLocation(87, 15),
// (95,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(95, 15),
// (96,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(96, 15),
// (104,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(104, 15),
// (105,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(105, 15),
// (112,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum", "long").WithLocation(112, 15),
// (113,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum").WithLocation(113, 15),
// (120,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum?", "long").WithLocation(120, 15),
// (121,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum?").WithLocation(121, 15)
);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_12()
{
string source = @"
enum TestEnum : int
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
short b = 1;
int c = 1;
short f = 0;
int g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test2()
{
TestEnum? x = 0;
short b = 1;
int c = 1;
short f = 0;
int g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test3()
{
TestEnum x = 0;
short? b = 1;
int? c = 1;
short? f = 0;
int? g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test4()
{
TestEnum? x = 0;
short? b = 1;
int? c = 1;
short? f = 0;
int? g = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
}
static void Test5()
{
TestEnum x = 0;
const short b = 1;
const int c = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const short b = 1;
const int c = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
System.Int32
TestEnum
System.Int32
TestEnum
TestEnum
System.Int32
System.Int32
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
TestEnum
TestEnum
System.Int32
TestEnum
System.Int32
TestEnum
TestEnum
System.Int32
System.Int32
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
TestEnum
TestEnum
TestEnum
System.Int32
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int32]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_13()
{
string source = @"
enum TestEnum : int
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
}
static void Test1()
{
TestEnum x = 0;
long d = 1;
long h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
long d = 1;
long h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
long? d = 1;
long? h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
long? d = 1;
long? h = 0;
Print(x - d);
Print(x - h);
Print(d - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test6()
{
TestEnum? x = 0;
const long d = 1;
Print(x - d);
Print(d - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (long)1);
Print((long)1 - x);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (24,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(24, 15),
// (25,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long").WithLocation(25, 15),
// (26,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(26, 15),
// (27,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum").WithLocation(27, 15),
// (36,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(36, 15),
// (37,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long").WithLocation(37, 15),
// (38,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(38, 15),
// (39,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long", "TestEnum?").WithLocation(39, 15),
// (48,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long?").WithLocation(48, 15),
// (49,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum", "long?").WithLocation(49, 15),
// (50,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum").WithLocation(50, 15),
// (51,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum").WithLocation(51, 15),
// (60,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long?").WithLocation(60, 15),
// (61,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long?'
// Print(x - h);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - h").WithArguments("-", "TestEnum?", "long?").WithLocation(61, 15),
// (62,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long?", "TestEnum?").WithLocation(62, 15),
// (63,15): error CS0019: Operator '-' cannot be applied to operands of type 'long?' and 'TestEnum?'
// Print(h - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "h - x").WithArguments("-", "long?", "TestEnum?").WithLocation(63, 15),
// (71,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum", "long").WithLocation(71, 15),
// (72,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum").WithLocation(72, 15),
// (80,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - d);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - d").WithArguments("-", "TestEnum?", "long").WithLocation(80, 15),
// (81,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print(d - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d - x").WithArguments("-", "long", "TestEnum?").WithLocation(81, 15),
// (88,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum", "long").WithLocation(88, 15),
// (89,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum").WithLocation(89, 15),
// (96,15): error CS0019: Operator '-' cannot be applied to operands of type 'TestEnum?' and 'long'
// Print(x - (long)1);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "x - (long)1").WithArguments("-", "TestEnum?", "long").WithLocation(96, 15),
// (97,15): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'TestEnum?'
// Print((long)1 - x);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "(long)1 - x").WithArguments("-", "long", "TestEnum?").WithLocation(97, 15)
);
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_14()
{
string source = @"
enum TestEnum : long
{
A, B
}
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
Test10();
}
static void Test1()
{
TestEnum x = 0;
short b = 1;
int c = 1;
long d = 1;
short f = 0;
int g = 0;
long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test2()
{
TestEnum? x = 0;
short b = 1;
int c = 1;
long d = 1;
short f = 0;
int g = 0;
long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test3()
{
TestEnum x = 0;
short? b = 1;
int? c = 1;
long? d = 1;
short? f = 0;
int? g = 0;
long? h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test4()
{
TestEnum? x = 0;
short? b = 1;
int? c = 1;
long? d = 1;
short? f = 0;
int? g = 0;
long? h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test5()
{
TestEnum x = 0;
const short b = 1;
const int c = 1;
const long d = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test6()
{
TestEnum? x = 0;
const short b = 1;
const int c = 1;
const long d = 1;
const short f = 0;
const int g = 0;
const long h = 0;
Print(x - b);
Print(x - c);
Print(x - d);
Print(x - f);
Print(x - g);
Print(x - h);
Print(b - x);
Print(c - x);
Print(d - x);
Print(f - x);
Print(g - x);
Print(h - x);
}
static void Test7()
{
TestEnum x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (long)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((long)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test8()
{
TestEnum? x = 0;
Print(x - (short)1);
Print(x - (int)1);
Print(x - (long)1);
Print(x - (short)0);
Print(x - (int)0);
Print(x - (long)0);
Print((short)1 - x);
Print((int)1 - x);
Print((long)1 - x);
Print((short)0 - x);
Print((int)0 - x);
Print((long)0 - x);
}
static void Test9()
{
TestEnum x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
static void Test10()
{
TestEnum? x = 0;
Print(x - 1);
Print(x - 0);
Print(1 - x);
Print(0 - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
TestEnum
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
TestEnum
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
TestEnum
TestEnum
TestEnum
TestEnum
System.Int64
System.Int64
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
TestEnum
System.Int64
TestEnum
System.Int64
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
System.Nullable`1[TestEnum]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_15()
{
string source = @"
enum TestEnumShort : short
{}
enum TestEnumInt : int
{ }
enum TestEnumLong : long
{ }
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
}
static void Test1()
{
TestEnumShort? x = 0;
Print(x - null);
Print(null - x);
}
static void Test2()
{
TestEnumInt? x = 0;
Print(x - null);
Print(null - x);
}
static void Test3()
{
TestEnumLong? x = 0;
Print(x - null);
Print(null - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")]
public void Bug1036392_16()
{
string source = @"
enum TestEnumShort : short
{}
enum TestEnumInt : int
{ }
enum TestEnumLong : long
{ }
class Program
{
static void Print<T>(T t)
{
System.Console.WriteLine(typeof(T));
}
static void Main(string[] args)
{
Test1();
Test2();
Test3();
}
static void Test1()
{
TestEnumShort x = 0;
Print(x - null);
Print(null - x);
}
static void Test2()
{
TestEnumInt x = 0;
Print(x - null);
Print(null - x);
}
static void Test3()
{
TestEnumLong x = 0;
Print(x - null);
Print(null - x);
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Nullable`1[System.Int16]
System.Nullable`1[System.Int16]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int32]
System.Nullable`1[System.Int64]
System.Nullable`1[System.Int64]
");
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_01()
{
string source = @"
class Test
{
static void Main()
{
Test0();
Test1();
Test2();
Test3();
Test4();
}
static void Test0()
{
Print(((System.TypeCode)0) as int?);
Print(0 as int?);
Print(((int?)0) as int?);
Print(0 as long?);
Print(0 as ulong?);
Print(GetNullableInt() as long?);
}
static int? GetNullableInt()
{
return 0;
}
static void Test1()
{
var c1 = new C1<int>();
c1.M1(0);
}
static void Test2()
{
var c1 = new C1<ulong>();
c1.M1<ulong>(0);
}
static void Test3()
{
var c1 = new C2();
c1.M1(0);
}
static void Test4()
{
var c1 = new C3();
c1.M1<int?>(0);
}
public static void Print<T>(T? v) where T : struct
{
System.Console.WriteLine(v.HasValue);
}
}
class C1<T>
{
public virtual void M1<S>(S x) where S :T
{
Test.Print(x as ulong?);
}
}
class C2 : C1<int>
{
public override void M1<S>(S x)
{
Test.Print(x as ulong?);
}
}
class C3 : C1<int?>
{
public override void M1<S>(S x)
{
Test.Print(x as ulong?);
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput:
@"False
True
True
False
False
False
False
True
False
False
");
verifier.VerifyIL("Test.Test0",
@"
{
// Code size 85 (0x55)
.maxstack 1
.locals init (int? V_0,
long? V_1,
ulong? V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""int?""
IL_0008: ldloc.0
IL_0009: call ""void Test.Print<int>(int?)""
IL_000e: ldc.i4.0
IL_000f: newobj ""int?..ctor(int)""
IL_0014: call ""void Test.Print<int>(int?)""
IL_0019: ldc.i4.0
IL_001a: newobj ""int?..ctor(int)""
IL_001f: call ""void Test.Print<int>(int?)""
IL_0024: ldloca.s V_1
IL_0026: initobj ""long?""
IL_002c: ldloc.1
IL_002d: call ""void Test.Print<long>(long?)""
IL_0032: ldloca.s V_2
IL_0034: initobj ""ulong?""
IL_003a: ldloc.2
IL_003b: call ""void Test.Print<ulong>(ulong?)""
IL_0040: call ""int? Test.GetNullableInt()""
IL_0045: pop
IL_0046: ldloca.s V_1
IL_0048: initobj ""long?""
IL_004e: ldloc.1
IL_004f: call ""void Test.Print<long>(long?)""
IL_0054: ret
}");
verifier.VerifyIL("C1<T>.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyIL("C2.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyIL("C3.M1<S>",
@"
{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""S""
IL_0006: isinst ""ulong?""
IL_000b: unbox.any ""ulong?""
IL_0010: call ""void Test.Print<ulong>(ulong?)""
IL_0015: ret
}");
verifier.VerifyDiagnostics(
// (15,15): warning CS0458: The result of the expression is always 'null' of type 'int?'
// Print(((System.TypeCode)0) as int?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "((System.TypeCode)0) as int?").WithArguments("int?").WithLocation(15, 15),
// (18,15): warning CS0458: The result of the expression is always 'null' of type 'long?'
// Print(0 as long?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "0 as long?").WithArguments("long?").WithLocation(18, 15),
// (19,15): warning CS0458: The result of the expression is always 'null' of type 'ulong?'
// Print(0 as ulong?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "0 as ulong?").WithArguments("ulong?").WithLocation(19, 15),
// (20,15): warning CS0458: The result of the expression is always 'null' of type 'long?'
// Print(GetNullableInt() as long?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "GetNullableInt() as long?").WithArguments("long?").WithLocation(20, 15)
);
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_02()
{
string source = @"
using System;
class Program
{
static void Main()
{
var x = 0 as long?;
Console.WriteLine(x.HasValue);
var y = 0 as ulong?;
Console.WriteLine(y.HasValue);
}
}
";
CompileAndVerify(source: source, expectedOutput:
@"False
False
");
}
[Fact, WorkItem(1090786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1090786")]
public void Bug1090786_03()
{
string source = @"
class Test
{
static void Main()
{
Test0();
}
static void Test0()
{
var c2 = new C2();
c2.M1<C1>(null);
}
public static void Print<T>(T v) where T : class
{
System.Console.WriteLine(v != null);
}
}
class C1
{}
class C2
{
public void M1<S>(C1 x) where S : C1
{
Test.Print(x as S);
Test.Print(((C1)null) as S);
}
}";
var verifier = CompileAndVerify(source: source, expectedOutput:
@"False
False
");
verifier.VerifyIL("C2.M1<S>",
@"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (S V_0)
IL_0000: ldarg.1
IL_0001: isinst ""S""
IL_0006: unbox.any ""S""
IL_000b: call ""void Test.Print<S>(S)""
IL_0010: ldloca.s V_0
IL_0012: initobj ""S""
IL_0018: ldloc.0
IL_0019: call ""void Test.Print<S>(S)""
IL_001e: ret
}");
}
[Fact, WorkItem(2075, "https://github.com/dotnet/roslyn/issues/2075")]
public void NegateALiteral()
{
string source = @"
using System;
namespace roslynChanges
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ((-(2147483648)).GetType ());
Console.WriteLine ((-2147483648).GetType ());
}
}
}";
CompileAndVerify(source: source, expectedOutput:
@"System.Int64
System.Int32
");
}
[Fact, WorkItem(4132, "https://github.com/dotnet/roslyn/issues/4132")]
public void Issue4132()
{
string source = @"
using System;
namespace NullableMathRepro
{
class Program
{
static void Main(string[] args)
{
int? x = 0;
x += 5;
Console.WriteLine(""'x' is {0}"", x);
IntHolder? y = 0;
y += 5;
Console.WriteLine(""'y' is {0}"", y);
}
}
struct IntHolder
{
private int x;
public static implicit operator int (IntHolder ih)
{
Console.WriteLine(""operator int (IntHolder ih)"");
return ih.x;
}
public static implicit operator IntHolder(int i)
{
Console.WriteLine(""operator IntHolder(int i)"");
return new IntHolder { x = i };
}
public override string ToString()
{
return x.ToString();
}
}
}";
CompileAndVerify(source: source, expectedOutput:
@"'x' is 5
operator IntHolder(int i)
operator int (IntHolder ih)
operator IntHolder(int i)
'y' is 5");
}
[Fact, WorkItem(8190, "https://github.com/dotnet/roslyn/issues/8190")]
public void Issue8190_1()
{
string source = @"
using System;
namespace RoslynNullableStringRepro
{
public class Program
{
public static void Main(string[] args)
{
NonNullableString? irony = ""abc"";
irony += ""def"";
string ynori = ""abc"";
ynori += (NonNullableString?)""def"";
Console.WriteLine(irony);
Console.WriteLine(ynori);
ynori += (NonNullableString?) null;
Console.WriteLine(ynori);
}
}
struct NonNullableString
{
NonNullableString(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
this.value = value;
}
readonly string value;
public override string ToString() => value;
public static implicit operator string(NonNullableString self) => self.value;
public static implicit operator NonNullableString(string value) => new NonNullableString(value);
public static string operator +(NonNullableString lhs, NonNullableString rhs) => lhs.value + rhs.value;
}
}";
CompileAndVerify(source: source, expectedOutput: "abcdef" + Environment.NewLine + "abcdef" + Environment.NewLine + "abcdef");
}
[Fact, WorkItem(8190, "https://github.com/dotnet/roslyn/issues/8190")]
public void Issue8190_2()
{
string source = @"
using System;
namespace RoslynNullableIntRepro
{
public class Program
{
public static void Main(string[] args)
{
NonNullableInt? irony = 1;
irony += 2;
int? ynori = 1;
ynori += (NonNullableInt?) 2;
Console.WriteLine(irony);
Console.WriteLine(ynori);
ynori += (NonNullableInt?) null;
Console.WriteLine(ynori);
}
}
struct NonNullableInt
{
NonNullableInt(int? value)
{
if (value == null)
{
throw new ArgumentNullException();
}
this.value = value;
}
readonly int? value;
public override string ToString() {return value.ToString();}
public static implicit operator int? (NonNullableInt self) {return self.value;}
public static implicit operator NonNullableInt(int? value) {return new NonNullableInt(value);}
public static int? operator +(NonNullableInt lhs, NonNullableInt rhs) { return lhs.value + rhs.value; }
}
}";
CompileAndVerify(source: source, expectedOutput: "3" + Environment.NewLine + "3" + Environment.NewLine);
}
[Fact, WorkItem(4027, "https://github.com/dotnet/roslyn/issues/4027")]
public void NotSignExtendedOperand()
{
string source = @"
class MainClass
{
public static void Main ()
{
short a = 0;
int b = 0;
a |= (short)b;
a = (short)(a | (short)b);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
}
[Fact]
[WorkItem(12345, "https://github.com/dotnet/roslyn/issues/12345")]
public void Bug12345()
{
string source = @"
class EnumRepro
{
public static void Main()
{
EnumWrapper<FlagsEnum> wrappedEnum = FlagsEnum.Goo;
wrappedEnum |= FlagsEnum.Bar;
System.Console.Write(wrappedEnum.Enum);
}
}
public struct EnumWrapper<T>
where T : struct
{
public T? Enum { get; private set; }
public static implicit operator T? (EnumWrapper<T> safeEnum)
{
return safeEnum.Enum;
}
public static implicit operator EnumWrapper<T>(T source)
{
return new EnumWrapper<T> { Enum = source };
}
}
[System.Flags]
public enum FlagsEnum
{
None = 0,
Goo = 1,
Bar = 2,
}
";
var verifier = CompileAndVerify(source, expectedOutput: "Goo, Bar");
verifier.VerifyDiagnostics();
}
[Fact]
public void IsWarningWithNonNullConstant()
{
var source =
@"class Program
{
public static void Main(string[] args)
{
const string d = ""goo"";
var x = d is string;
}
}
";
var compilation = CreateCompilation(source)
.VerifyDiagnostics(
// (6,17): warning CS0183: The given expression is always of the provided ('string') type
// var x = d is string;
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "d is string").WithArguments("string").WithLocation(6, 17)
);
}
[Fact, WorkItem(19310, "https://github.com/dotnet/roslyn/issues/19310")]
public void IsWarningWithTupleConversion()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var t = (x: 1, y: 2);
if (t is ValueTuple<long, int>) { } // too big
if (t is ValueTuple<short, int>) { } // too small
if (t is ValueTuple<int, int>) { } // goldilocks
}
}";
var compilation = CreateCompilationWithMscorlib40(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef })
.VerifyDiagnostics(
// (7,13): warning CS0184: The given expression is never of the provided ('(long, int)') type
// if (t is ValueTuple<long, int>) { } // too big
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is ValueTuple<long, int>").WithArguments("(long, int)").WithLocation(7, 13),
// (8,13): warning CS0184: The given expression is never of the provided ('(short, int)') type
// if (t is ValueTuple<short, int>) { } // too small
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "t is ValueTuple<short, int>").WithArguments("(short, int)").WithLocation(8, 13),
// (9,13): warning CS0183: The given expression is always of the provided ('(int, int)') type
// if (t is ValueTuple<int, int>) { } // goldilocks
Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "t is ValueTuple<int, int>").WithArguments("(int, int)").WithLocation(9, 13)
);
}
[Fact, WorkItem(21486, "https://github.com/dotnet/roslyn/issues/21486")]
public void TypeOfErrorUnaryOperator()
{
var source =
@"
public class C {
public void M2() {
var local = !invalidExpression;
if (local) { }
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (4,22): error CS0103: The name 'invalidExpression' does not exist in the current context
// var local = !invalidExpression;
Diagnostic(ErrorCode.ERR_NameNotInContext, "invalidExpression").WithArguments("invalidExpression").WithLocation(4, 22)
);
var tree = compilation.SyntaxTrees.Single();
var negNode = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single();
Assert.Equal("!invalidExpression", negNode.ToString());
var type = (ITypeSymbol)compilation.GetSemanticModel(tree).GetTypeInfo(negNode).Type;
Assert.Equal("?", type.ToTestDisplayString());
Assert.True(type.IsErrorType());
}
// Attempting to call `ConstantValue` on every constituent string component realizes every string, effectively
// replicating the original O(n^2) bug that this test is demonstrating is fixed.
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(43019, "https://github.com/dotnet/roslyn/issues/43019"), WorkItem(529600, "DevDiv"), WorkItem(7398, "https://github.com/dotnet/roslyn/issues/7398")]
public void Bug529600()
{
// History of this bug: When constant folding a long sequence of string concatentations, there is
// an intermediate constant value for every left-hand operand. So the total memory consumed to
// compute the whole concatenation was O(n^2). The compiler would simply perform this work and
// eventually run out of memory, simply crashing with no useful diagnostic. Later, the concatenation
// implementation was instrumented so it would detect when it was likely to run out of memory soon,
// and would instead report a diagnostic at the last step. This test was added to demonstrate that
// we produced a diagnostic. However, the compiler still consumed O(n^2) memory for the
// concatenation and this test used to consume so much memory that it would cause other tests running
// in parallel to fail because they might not have enough memory to succeed. So the test was
// disabled and eventually removed. The compiler would still crash with programs containing large
// string concatenations, so the underlying problem had not been addressed. Now we have revised the
// implementation of constant folding so that it requires O(n) memory. As a consequence this test now
// runs very quickly and does not consume gobs of memory.
string source = $@"
class M
{{
static void Main()
{{}}
const string C0 = ""{new string('0', 65000)}"";
const string C1 = C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 + C0 +
C0;
const string C2 = C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
C1;
}}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (28,68): error CS8095: Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.
// C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 + C1 +
Diagnostic(ErrorCode.ERR_ConstantStringTooLong, "C1").WithLocation(28, 68)
);
// If we realize every string constant value when each IOperation is created, then attempting to enumerate all
// IOperations will consume O(n^2) memory. This demonstrates that these values are not eagerly created, and the
// test runs quickly and without issue
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var fieldInitializerOperations = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>()
.Select(v => v.Initializer.Value)
.Select(i => model.GetOperation(i));
int numChildren = 0;
foreach (var initializerOp in fieldInitializerOperations)
{
enumerateChildren(initializerOp);
}
Assert.Equal(1203, numChildren);
void enumerateChildren(IOperation iop)
{
numChildren++;
Assert.NotNull(iop);
foreach (var child in iop.Children)
{
enumerateChildren(child);
}
}
}
[Fact, WorkItem(39975, "https://github.com/dotnet/roslyn/issues/39975")]
public void EnsureOperandsConvertedInErrorExpression_01()
{
string source =
@"class C
{
static unsafe void M(dynamic d, int* p)
{
d += p;
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics(
// (5,9): error CS0019: Operator '+=' cannot be applied to operands of type 'dynamic' and 'int*'
// d += p;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "d += p").WithArguments("+=", "dynamic", "int*").WithLocation(5, 9)
);
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/Test/Resources/Core/SymbolsTests/Interface/MDInterfaceMapping.cs | // Licensed to the .NET Foundation under one or more 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 /t:library
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public interface IGoo
{
void Goo();
}
public class A
{
public void Goo() { Console.WriteLine("A.Goo"); }
}
public class B : A, IGoo
{
}
public class C : B
{
public new void Goo() { Console.WriteLine("C.Goo"); }
}
| // Licensed to the .NET Foundation under one or more 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 /t:library
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public interface IGoo
{
void Goo();
}
public class A
{
public void Goo() { Console.WriteLine("A.Goo"); }
}
public class B : A, IGoo
{
}
public class C : B
{
public new void Goo() { Console.WriteLine("C.Goo"); }
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Dependencies/Collections/SegmentedArray.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Collections.Internal;
namespace Microsoft.CodeAnalysis.Collections
{
internal static class SegmentedArray
{
/// <seealso cref="Array.Clear(Array, int, int)"/>
internal static void Clear<T>(SegmentedArray<T> array, int index, int length)
{
foreach (var memory in array.GetSegments(index, length))
{
memory.Span.Clear();
}
}
/// <seealso cref="Array.Copy(Array, Array, int)"/>
internal static void Copy<T>(SegmentedArray<T> sourceArray, SegmentedArray<T> destinationArray, int length)
{
if (length == 0)
return;
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
if (length > sourceArray.Length)
throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
if (length > destinationArray.Length)
throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray));
foreach (var (first, second) in GetSegments(sourceArray, destinationArray, length))
{
first.CopyTo(second);
}
}
public static void Copy<T>(SegmentedArray<T> sourceArray, Array destinationArray, int length)
{
if (destinationArray is null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray);
if (length == 0)
return;
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
if (length > sourceArray.Length)
throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
if (length > destinationArray.Length)
throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray));
var copied = 0;
foreach (var memory in sourceArray.GetSegments(0, length))
{
if (!MemoryMarshal.TryGetArray<T>(memory, out var segment))
{
throw new NotSupportedException();
}
Array.Copy(segment.Array!, sourceIndex: segment.Offset, destinationArray: destinationArray, destinationIndex: copied, length: segment.Count);
copied += segment.Count;
}
}
public static void Copy<T>(SegmentedArray<T> sourceArray, int sourceIndex, SegmentedArray<T> destinationArray, int destinationIndex, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_ArrayLB);
if (destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_ArrayLB);
if ((uint)(sourceIndex + length) > sourceArray.Length)
throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
if ((uint)(destinationIndex + length) > destinationArray.Length)
throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray));
if (length == 0)
return;
if (sourceArray.SyncRoot == destinationArray.SyncRoot
&& sourceIndex + length > destinationIndex)
{
// We are copying in the same array with overlap
CopyOverlapped(sourceArray, sourceIndex, destinationIndex, length);
}
else
{
foreach (var (first, second) in GetSegmentsUnaligned(sourceArray, sourceIndex, destinationArray, destinationIndex, length))
{
first.CopyTo(second);
}
}
}
// PERF: Avoid inlining this path in Copy<T>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CopyOverlapped<T>(SegmentedArray<T> array, int sourceIndex, int destinationIndex, int length)
{
Debug.Assert(length > 0);
Debug.Assert(sourceIndex >= 0);
Debug.Assert(destinationIndex >= 0);
Debug.Assert((uint)(sourceIndex + length) <= array.Length);
Debug.Assert((uint)(destinationIndex + length) <= array.Length);
var unalignedEnumerator = GetSegmentsUnaligned(array, sourceIndex, array, destinationIndex, length);
if (sourceIndex < destinationIndex)
{
// We are copying forward in the same array with overlap
foreach (var (first, second) in unalignedEnumerator.Reverse())
{
first.CopyTo(second);
}
}
else
{
foreach (var (first, second) in unalignedEnumerator)
{
first.CopyTo(second);
}
}
}
public static void Copy<T>(SegmentedArray<T> sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
if (destinationArray == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray);
if (typeof(T[]) != destinationArray.GetType() && destinationArray.Rank != 1)
throw new RankException(SR.Rank_MustMatch);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_ArrayLB);
var dstLB = destinationArray.GetLowerBound(0);
if (destinationIndex < dstLB || destinationIndex - dstLB < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_ArrayLB);
destinationIndex -= dstLB;
if ((uint)(sourceIndex + length) > sourceArray.Length)
throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
if ((uint)(destinationIndex + length) > (nuint)destinationArray.LongLength)
throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray));
var copied = 0;
foreach (var memory in sourceArray.GetSegments(sourceIndex, length))
{
if (!MemoryMarshal.TryGetArray<T>(memory, out var segment))
{
throw new NotSupportedException();
}
Array.Copy(segment.Array!, sourceIndex: segment.Offset, destinationArray: destinationArray, destinationIndex: destinationIndex + copied, length: segment.Count);
copied += segment.Count;
}
}
public static int BinarySearch<T>(SegmentedArray<T> array, T value)
{
return BinarySearch(array, 0, array.Length, value, comparer: null);
}
public static int BinarySearch<T>(SegmentedArray<T> array, T value, IComparer<T>? comparer)
{
return BinarySearch(array, 0, array.Length, value, comparer);
}
public static int BinarySearch<T>(SegmentedArray<T> array, int index, int length, T value)
{
return BinarySearch(array, index, length, value, comparer: null);
}
public static int BinarySearch<T>(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer)
{
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
return SegmentedArraySortHelper<T>.BinarySearch(array, index, length, value, comparer);
}
public static int IndexOf<T>(SegmentedArray<T> array, T value)
{
return IndexOf(array, value, 0, array.Length, comparer: null);
}
public static int IndexOf<T>(SegmentedArray<T> array, T value, int startIndex)
{
return IndexOf(array, value, startIndex, array.Length - startIndex, comparer: null);
}
public static int IndexOf<T>(SegmentedArray<T> array, T value, int startIndex, int count)
{
return IndexOf(array, value, startIndex, count, comparer: null);
}
public static int IndexOf<T>(SegmentedArray<T> array, T value, int startIndex, int count, IEqualityComparer<T>? comparer)
{
if ((uint)startIndex > (uint)array.Length)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if ((uint)count > (uint)(array.Length - startIndex))
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
var offset = startIndex;
foreach (var memory in array.GetSegments(startIndex, count))
{
if (!MemoryMarshal.TryGetArray<T>(memory, out var segment))
{
throw new NotSupportedException();
}
int index;
if (comparer is null || comparer == EqualityComparer<T>.Default)
{
index = Array.IndexOf(segment.Array!, value, segment.Offset, segment.Count);
}
else
{
index = -1;
var endIndex = segment.Offset + segment.Count;
for (var i = segment.Offset; i < endIndex; i++)
{
if (comparer.Equals(array[i], value))
{
index = i;
break;
}
}
}
if (index >= 0)
{
return index + offset - segment.Offset;
}
offset += segment.Count;
}
return -1;
}
public static int LastIndexOf<T>(SegmentedArray<T> array, T value)
{
return LastIndexOf(array, value, array.Length - 1, array.Length, comparer: null);
}
public static int LastIndexOf<T>(SegmentedArray<T> array, T value, int startIndex)
{
return LastIndexOf(array, value, startIndex, array.Length == 0 ? 0 : startIndex + 1, comparer: null);
}
public static int LastIndexOf<T>(SegmentedArray<T> array, T value, int startIndex, int count)
{
return LastIndexOf(array, value, startIndex, count, comparer: null);
}
public static int LastIndexOf<T>(SegmentedArray<T> array, T value, int startIndex, int count, IEqualityComparer<T>? comparer)
{
if (array.Length == 0)
{
// Special case for 0 length List
// accept -1 and 0 as valid startIndex for compatibility reason.
if (startIndex != -1 && startIndex != 0)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
// only 0 is a valid value for count if array is empty
if (count != 0)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
return -1;
}
// Make sure we're not out of range
if ((uint)startIndex >= (uint)array.Length)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
if (comparer is null || comparer == EqualityComparer<T>.Default)
{
var endIndex = startIndex - count + 1;
for (var i = startIndex; i >= endIndex; i--)
{
if (EqualityComparer<T>.Default.Equals(array[i], value))
return i;
}
}
else
{
var endIndex = startIndex - count + 1;
for (var i = startIndex; i >= endIndex; i--)
{
if (comparer.Equals(array[i], value))
return i;
}
}
return -1;
}
public static void Reverse<T>(SegmentedArray<T> array)
{
Reverse(array, 0, array.Length);
}
public static void Reverse<T>(SegmentedArray<T> array, int index, int length)
{
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (length <= 1)
return;
var firstIndex = index;
var lastIndex = index + length - 1;
do
{
var temp = array[firstIndex];
array[firstIndex] = array[lastIndex];
array[lastIndex] = temp;
firstIndex++;
lastIndex--;
} while (firstIndex < lastIndex);
}
public static void Sort<T>(SegmentedArray<T> array)
{
if (array.Length > 1)
{
var segment = new SegmentedArraySegment<T>(array, 0, array.Length);
SegmentedArraySortHelper<T>.Sort(segment, (IComparer<T>?)null);
}
}
public static void Sort<T>(SegmentedArray<T> array, int index, int length)
{
Sort(array, index, length, comparer: null);
}
public static void Sort<T>(SegmentedArray<T> array, IComparer<T>? comparer)
{
Sort(array, 0, array.Length, comparer);
}
public static void Sort<T>(SegmentedArray<T> array, int index, int length, IComparer<T>? comparer)
{
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (length > 1)
{
var segment = new SegmentedArraySegment<T>(array, index, length);
SegmentedArraySortHelper<T>.Sort(segment, comparer);
}
}
public static void Sort<T>(SegmentedArray<T> array, Comparison<T> comparison)
{
if (comparison is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
if (array.Length > 1)
{
var segment = new SegmentedArraySegment<T>(array, 0, array.Length);
SegmentedArraySortHelper<T>.Sort(segment, comparison);
}
}
private static SegmentEnumerable<T> GetSegments<T>(this SegmentedArray<T> array, int offset, int length)
=> new(array, offset, length);
private static AlignedSegmentEnumerable<T> GetSegments<T>(SegmentedArray<T> first, SegmentedArray<T> second, int length)
=> new(first, second, length);
#pragma warning disable IDE0051 // Remove unused private members (will be used in follow-up)
private static AlignedSegmentEnumerable<T> GetSegmentsAligned<T>(SegmentedArray<T> first, int firstOffset, SegmentedArray<T> second, int secondOffset, int length)
=> new(first, firstOffset, second, secondOffset, length);
#pragma warning restore IDE0051 // Remove unused private members
private static UnalignedSegmentEnumerable<T> GetSegmentsUnaligned<T>(SegmentedArray<T> first, int firstOffset, SegmentedArray<T> second, int secondOffset, int length)
=> new(first, firstOffset, second, secondOffset, length);
private readonly struct AlignedSegmentEnumerable<T>
{
private readonly SegmentedArray<T> _first;
private readonly int _firstOffset;
private readonly SegmentedArray<T> _second;
private readonly int _secondOffset;
private readonly int _length;
public AlignedSegmentEnumerable(SegmentedArray<T> first, SegmentedArray<T> second, int length)
: this(first, 0, second, 0, length)
{
}
public AlignedSegmentEnumerable(SegmentedArray<T> first, int firstOffset, SegmentedArray<T> second, int secondOffset, int length)
{
_first = first;
_firstOffset = firstOffset;
_second = second;
_secondOffset = secondOffset;
_length = length;
}
public AlignedSegmentEnumerator<T> GetEnumerator()
=> new((T[][])_first.SyncRoot, _firstOffset, (T[][])_second.SyncRoot, _secondOffset, _length);
}
private struct AlignedSegmentEnumerator<T>
{
private readonly T[][] _firstSegments;
private readonly int _firstOffset;
private readonly T[][] _secondSegments;
private readonly int _secondOffset;
private readonly int _length;
private int _completed;
private (Memory<T> first, Memory<T> second) _current;
public AlignedSegmentEnumerator(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length)
{
_firstSegments = firstSegments;
_firstOffset = firstOffset;
_secondSegments = secondSegments;
_secondOffset = secondOffset;
_length = length;
_completed = 0;
_current = (Memory<T>.Empty, Memory<T>.Empty);
}
public (Memory<T> first, Memory<T> second) Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = (Memory<T>.Empty, Memory<T>.Empty);
return false;
}
if (_completed == 0)
{
var initialFirstSegment = _firstOffset >> SegmentedArrayHelper.GetSegmentShift<T>();
var initialSecondSegment = _secondOffset >> SegmentedArrayHelper.GetSegmentShift<T>();
var offset = _firstOffset & SegmentedArrayHelper.GetOffsetMask<T>();
Debug.Assert(offset == (_secondOffset & SegmentedArrayHelper.GetOffsetMask<T>()), "Aligned views must start at the same segment offset");
var firstSegment = _firstSegments[initialFirstSegment];
var secondSegment = _secondSegments[initialSecondSegment];
var remainingInSegment = firstSegment.Length - offset;
var currentSegmentLength = Math.Min(remainingInSegment, _length);
_current = (firstSegment.AsMemory().Slice(offset, currentSegmentLength), secondSegment.AsMemory().Slice(offset, currentSegmentLength));
_completed = currentSegmentLength;
return true;
}
else
{
var firstSegment = _firstSegments[(_completed + _firstOffset) >> SegmentedArrayHelper.GetSegmentShift<T>()];
var secondSegment = _secondSegments[(_completed + _secondOffset) >> SegmentedArrayHelper.GetSegmentShift<T>()];
var currentSegmentLength = Math.Min(SegmentedArrayHelper.GetSegmentSize<T>(), _length - _completed);
_current = (firstSegment.AsMemory().Slice(0, currentSegmentLength), secondSegment.AsMemory().Slice(0, currentSegmentLength));
_completed += currentSegmentLength;
return true;
}
}
}
private readonly struct UnalignedSegmentEnumerable<T>
{
private readonly SegmentedArray<T> _first;
private readonly int _firstOffset;
private readonly SegmentedArray<T> _second;
private readonly int _secondOffset;
private readonly int _length;
public UnalignedSegmentEnumerable(SegmentedArray<T> first, SegmentedArray<T> second, int length)
: this(first, 0, second, 0, length)
{
}
public UnalignedSegmentEnumerable(SegmentedArray<T> first, int firstOffset, SegmentedArray<T> second, int secondOffset, int length)
{
_first = first;
_firstOffset = firstOffset;
_second = second;
_secondOffset = secondOffset;
_length = length;
}
public UnalignedSegmentEnumerator<T> GetEnumerator()
=> new((T[][])_first.SyncRoot, _firstOffset, (T[][])_second.SyncRoot, _secondOffset, _length);
public ReverseEnumerable Reverse()
=> new(this);
public readonly struct ReverseEnumerable
{
private readonly UnalignedSegmentEnumerable<T> _enumerable;
public ReverseEnumerable(UnalignedSegmentEnumerable<T> enumerable)
{
_enumerable = enumerable;
}
public UnalignedSegmentEnumerator<T>.Reverse GetEnumerator()
=> new((T[][])_enumerable._first.SyncRoot, _enumerable._firstOffset, (T[][])_enumerable._second.SyncRoot, _enumerable._secondOffset, _enumerable._length);
public UnalignedSegmentEnumerable<T> Reverse()
=> _enumerable;
}
}
private struct UnalignedSegmentEnumerator<T>
{
private readonly T[][] _firstSegments;
private readonly int _firstOffset;
private readonly T[][] _secondSegments;
private readonly int _secondOffset;
private readonly int _length;
private int _completed;
private (Memory<T> first, Memory<T> second) _current;
public UnalignedSegmentEnumerator(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length)
{
_firstSegments = firstSegments;
_firstOffset = firstOffset;
_secondSegments = secondSegments;
_secondOffset = secondOffset;
_length = length;
_completed = 0;
_current = (Memory<T>.Empty, Memory<T>.Empty);
}
public (Memory<T> first, Memory<T> second) Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = (Memory<T>.Empty, Memory<T>.Empty);
return false;
}
var initialFirstSegment = (_completed + _firstOffset) >> SegmentedArrayHelper.GetSegmentShift<T>();
var initialSecondSegment = (_completed + _secondOffset) >> SegmentedArrayHelper.GetSegmentShift<T>();
var firstOffset = (_completed + _firstOffset) & SegmentedArrayHelper.GetOffsetMask<T>();
var secondOffset = (_completed + _secondOffset) & SegmentedArrayHelper.GetOffsetMask<T>();
var firstSegment = _firstSegments[initialFirstSegment];
var secondSegment = _secondSegments[initialSecondSegment];
var remainingInFirstSegment = firstSegment.Length - firstOffset;
var remainingInSecondSegment = secondSegment.Length - secondOffset;
var currentSegmentLength = Math.Min(Math.Min(remainingInFirstSegment, remainingInSecondSegment), _length - _completed);
_current = (firstSegment.AsMemory().Slice(firstOffset, currentSegmentLength), secondSegment.AsMemory().Slice(secondOffset, currentSegmentLength));
_completed += currentSegmentLength;
return true;
}
public struct Reverse
{
private readonly T[][] _firstSegments;
private readonly int _firstOffset;
private readonly T[][] _secondSegments;
private readonly int _secondOffset;
private readonly int _length;
private int _completed;
private (Memory<T> first, Memory<T> second) _current;
public Reverse(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length)
{
_firstSegments = firstSegments;
_firstOffset = firstOffset;
_secondSegments = secondSegments;
_secondOffset = secondOffset;
_length = length;
_completed = 0;
_current = (Memory<T>.Empty, Memory<T>.Empty);
}
public (Memory<T> first, Memory<T> second) Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = (Memory<T>.Empty, Memory<T>.Empty);
return false;
}
var initialFirstSegment = (_firstOffset + _length - _completed - 1) >> SegmentedArrayHelper.GetSegmentShift<T>();
var initialSecondSegment = (_secondOffset + _length - _completed - 1) >> SegmentedArrayHelper.GetSegmentShift<T>();
var firstOffset = (_firstOffset + _length - _completed - 1) & SegmentedArrayHelper.GetOffsetMask<T>();
var secondOffset = (_secondOffset + _length - _completed - 1) & SegmentedArrayHelper.GetOffsetMask<T>();
var firstSegment = _firstSegments[initialFirstSegment];
var secondSegment = _secondSegments[initialSecondSegment];
var remainingInFirstSegment = firstOffset + 1;
var remainingInSecondSegment = secondOffset + 1;
var currentSegmentLength = Math.Min(Math.Min(remainingInFirstSegment, remainingInSecondSegment), _length - _completed);
_current = (firstSegment.AsMemory().Slice(firstOffset - currentSegmentLength + 1, currentSegmentLength), secondSegment.AsMemory().Slice(secondOffset - currentSegmentLength + 1, currentSegmentLength));
_completed += currentSegmentLength;
return true;
}
}
}
private readonly struct SegmentEnumerable<T>
{
private readonly SegmentedArray<T> _array;
private readonly int _offset;
private readonly int _length;
public SegmentEnumerable(SegmentedArray<T> array)
{
_array = array;
_offset = 0;
_length = array.Length;
}
public SegmentEnumerable(SegmentedArray<T> array, int offset, int length)
{
if (offset < 0 || length < 0 || (uint)(offset + length) > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
_array = array;
_offset = offset;
_length = length;
}
public SegmentEnumerator<T> GetEnumerator()
=> new((T[][])_array.SyncRoot, _offset, _length);
public ReverseEnumerable Reverse()
=> new(this);
public readonly struct ReverseEnumerable
{
private readonly SegmentEnumerable<T> _enumerable;
public ReverseEnumerable(SegmentEnumerable<T> enumerable)
{
_enumerable = enumerable;
}
public SegmentEnumerator<T>.Reverse GetEnumerator()
=> new((T[][])_enumerable._array.SyncRoot, _enumerable._offset, _enumerable._length);
public SegmentEnumerable<T> Reverse()
=> _enumerable;
}
}
private struct SegmentEnumerator<T>
{
private readonly T[][] _segments;
private readonly int _offset;
private readonly int _length;
private int _completed;
private Memory<T> _current;
public SegmentEnumerator(T[][] segments, int offset, int length)
{
_segments = segments;
_offset = offset;
_length = length;
_completed = 0;
_current = Memory<T>.Empty;
}
public Memory<T> Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = Memory<T>.Empty;
return false;
}
if (_completed == 0)
{
var firstSegment = _offset >> SegmentedArrayHelper.GetSegmentShift<T>();
var offset = _offset & SegmentedArrayHelper.GetOffsetMask<T>();
var segment = _segments[firstSegment];
var remainingInSegment = segment.Length - offset;
_current = segment.AsMemory().Slice(offset, Math.Min(remainingInSegment, _length));
_completed = _current.Length;
return true;
}
else
{
var segment = _segments[(_completed + _offset) >> SegmentedArrayHelper.GetSegmentShift<T>()];
_current = segment.AsMemory().Slice(0, Math.Min(SegmentedArrayHelper.GetSegmentSize<T>(), _length - _completed));
_completed += _current.Length;
return true;
}
}
public struct Reverse
{
private readonly T[][] _segments;
private readonly int _offset;
private readonly int _length;
private int _completed;
private Memory<T> _current;
public Reverse(T[][] segments, int offset, int length)
{
_segments = segments;
_offset = offset;
_length = length;
_completed = 0;
_current = Memory<T>.Empty;
}
public Memory<T> Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = Memory<T>.Empty;
return false;
}
if (_completed == 0)
{
var firstSegment = _offset >> SegmentedArrayHelper.GetSegmentShift<T>();
var offset = _offset & SegmentedArrayHelper.GetOffsetMask<T>();
var segment = _segments[firstSegment];
var remainingInSegment = segment.Length - offset;
_current = segment.AsMemory().Slice(offset, Math.Min(remainingInSegment, _length));
_completed = _current.Length;
return true;
}
else
{
var segment = _segments[(_completed + _offset) >> SegmentedArrayHelper.GetSegmentShift<T>()];
_current = segment.AsMemory().Slice(0, Math.Min(SegmentedArrayHelper.GetSegmentSize<T>(), _length - _completed));
_completed += _current.Length;
return true;
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Collections.Internal;
namespace Microsoft.CodeAnalysis.Collections
{
internal static class SegmentedArray
{
/// <seealso cref="Array.Clear(Array, int, int)"/>
internal static void Clear<T>(SegmentedArray<T> array, int index, int length)
{
foreach (var memory in array.GetSegments(index, length))
{
memory.Span.Clear();
}
}
/// <seealso cref="Array.Copy(Array, Array, int)"/>
internal static void Copy<T>(SegmentedArray<T> sourceArray, SegmentedArray<T> destinationArray, int length)
{
if (length == 0)
return;
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
if (length > sourceArray.Length)
throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
if (length > destinationArray.Length)
throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray));
foreach (var (first, second) in GetSegments(sourceArray, destinationArray, length))
{
first.CopyTo(second);
}
}
public static void Copy<T>(SegmentedArray<T> sourceArray, Array destinationArray, int length)
{
if (destinationArray is null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray);
if (length == 0)
return;
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
if (length > sourceArray.Length)
throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
if (length > destinationArray.Length)
throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray));
var copied = 0;
foreach (var memory in sourceArray.GetSegments(0, length))
{
if (!MemoryMarshal.TryGetArray<T>(memory, out var segment))
{
throw new NotSupportedException();
}
Array.Copy(segment.Array!, sourceIndex: segment.Offset, destinationArray: destinationArray, destinationIndex: copied, length: segment.Count);
copied += segment.Count;
}
}
public static void Copy<T>(SegmentedArray<T> sourceArray, int sourceIndex, SegmentedArray<T> destinationArray, int destinationIndex, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_ArrayLB);
if (destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_ArrayLB);
if ((uint)(sourceIndex + length) > sourceArray.Length)
throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
if ((uint)(destinationIndex + length) > destinationArray.Length)
throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray));
if (length == 0)
return;
if (sourceArray.SyncRoot == destinationArray.SyncRoot
&& sourceIndex + length > destinationIndex)
{
// We are copying in the same array with overlap
CopyOverlapped(sourceArray, sourceIndex, destinationIndex, length);
}
else
{
foreach (var (first, second) in GetSegmentsUnaligned(sourceArray, sourceIndex, destinationArray, destinationIndex, length))
{
first.CopyTo(second);
}
}
}
// PERF: Avoid inlining this path in Copy<T>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void CopyOverlapped<T>(SegmentedArray<T> array, int sourceIndex, int destinationIndex, int length)
{
Debug.Assert(length > 0);
Debug.Assert(sourceIndex >= 0);
Debug.Assert(destinationIndex >= 0);
Debug.Assert((uint)(sourceIndex + length) <= array.Length);
Debug.Assert((uint)(destinationIndex + length) <= array.Length);
var unalignedEnumerator = GetSegmentsUnaligned(array, sourceIndex, array, destinationIndex, length);
if (sourceIndex < destinationIndex)
{
// We are copying forward in the same array with overlap
foreach (var (first, second) in unalignedEnumerator.Reverse())
{
first.CopyTo(second);
}
}
else
{
foreach (var (first, second) in unalignedEnumerator)
{
first.CopyTo(second);
}
}
}
public static void Copy<T>(SegmentedArray<T> sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
if (destinationArray == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray);
if (typeof(T[]) != destinationArray.GetType() && destinationArray.Rank != 1)
throw new RankException(SR.Rank_MustMatch);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_ArrayLB);
var dstLB = destinationArray.GetLowerBound(0);
if (destinationIndex < dstLB || destinationIndex - dstLB < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_ArrayLB);
destinationIndex -= dstLB;
if ((uint)(sourceIndex + length) > sourceArray.Length)
throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray));
if ((uint)(destinationIndex + length) > (nuint)destinationArray.LongLength)
throw new ArgumentException(SR.Arg_LongerThanDestArray, nameof(destinationArray));
var copied = 0;
foreach (var memory in sourceArray.GetSegments(sourceIndex, length))
{
if (!MemoryMarshal.TryGetArray<T>(memory, out var segment))
{
throw new NotSupportedException();
}
Array.Copy(segment.Array!, sourceIndex: segment.Offset, destinationArray: destinationArray, destinationIndex: destinationIndex + copied, length: segment.Count);
copied += segment.Count;
}
}
public static int BinarySearch<T>(SegmentedArray<T> array, T value)
{
return BinarySearch(array, 0, array.Length, value, comparer: null);
}
public static int BinarySearch<T>(SegmentedArray<T> array, T value, IComparer<T>? comparer)
{
return BinarySearch(array, 0, array.Length, value, comparer);
}
public static int BinarySearch<T>(SegmentedArray<T> array, int index, int length, T value)
{
return BinarySearch(array, index, length, value, comparer: null);
}
public static int BinarySearch<T>(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer)
{
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
return SegmentedArraySortHelper<T>.BinarySearch(array, index, length, value, comparer);
}
public static int IndexOf<T>(SegmentedArray<T> array, T value)
{
return IndexOf(array, value, 0, array.Length, comparer: null);
}
public static int IndexOf<T>(SegmentedArray<T> array, T value, int startIndex)
{
return IndexOf(array, value, startIndex, array.Length - startIndex, comparer: null);
}
public static int IndexOf<T>(SegmentedArray<T> array, T value, int startIndex, int count)
{
return IndexOf(array, value, startIndex, count, comparer: null);
}
public static int IndexOf<T>(SegmentedArray<T> array, T value, int startIndex, int count, IEqualityComparer<T>? comparer)
{
if ((uint)startIndex > (uint)array.Length)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if ((uint)count > (uint)(array.Length - startIndex))
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
var offset = startIndex;
foreach (var memory in array.GetSegments(startIndex, count))
{
if (!MemoryMarshal.TryGetArray<T>(memory, out var segment))
{
throw new NotSupportedException();
}
int index;
if (comparer is null || comparer == EqualityComparer<T>.Default)
{
index = Array.IndexOf(segment.Array!, value, segment.Offset, segment.Count);
}
else
{
index = -1;
var endIndex = segment.Offset + segment.Count;
for (var i = segment.Offset; i < endIndex; i++)
{
if (comparer.Equals(array[i], value))
{
index = i;
break;
}
}
}
if (index >= 0)
{
return index + offset - segment.Offset;
}
offset += segment.Count;
}
return -1;
}
public static int LastIndexOf<T>(SegmentedArray<T> array, T value)
{
return LastIndexOf(array, value, array.Length - 1, array.Length, comparer: null);
}
public static int LastIndexOf<T>(SegmentedArray<T> array, T value, int startIndex)
{
return LastIndexOf(array, value, startIndex, array.Length == 0 ? 0 : startIndex + 1, comparer: null);
}
public static int LastIndexOf<T>(SegmentedArray<T> array, T value, int startIndex, int count)
{
return LastIndexOf(array, value, startIndex, count, comparer: null);
}
public static int LastIndexOf<T>(SegmentedArray<T> array, T value, int startIndex, int count, IEqualityComparer<T>? comparer)
{
if (array.Length == 0)
{
// Special case for 0 length List
// accept -1 and 0 as valid startIndex for compatibility reason.
if (startIndex != -1 && startIndex != 0)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
// only 0 is a valid value for count if array is empty
if (count != 0)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
return -1;
}
// Make sure we're not out of range
if ((uint)startIndex >= (uint)array.Length)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
if (comparer is null || comparer == EqualityComparer<T>.Default)
{
var endIndex = startIndex - count + 1;
for (var i = startIndex; i >= endIndex; i--)
{
if (EqualityComparer<T>.Default.Equals(array[i], value))
return i;
}
}
else
{
var endIndex = startIndex - count + 1;
for (var i = startIndex; i >= endIndex; i--)
{
if (comparer.Equals(array[i], value))
return i;
}
}
return -1;
}
public static void Reverse<T>(SegmentedArray<T> array)
{
Reverse(array, 0, array.Length);
}
public static void Reverse<T>(SegmentedArray<T> array, int index, int length)
{
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (length <= 1)
return;
var firstIndex = index;
var lastIndex = index + length - 1;
do
{
var temp = array[firstIndex];
array[firstIndex] = array[lastIndex];
array[lastIndex] = temp;
firstIndex++;
lastIndex--;
} while (firstIndex < lastIndex);
}
public static void Sort<T>(SegmentedArray<T> array)
{
if (array.Length > 1)
{
var segment = new SegmentedArraySegment<T>(array, 0, array.Length);
SegmentedArraySortHelper<T>.Sort(segment, (IComparer<T>?)null);
}
}
public static void Sort<T>(SegmentedArray<T> array, int index, int length)
{
Sort(array, index, length, comparer: null);
}
public static void Sort<T>(SegmentedArray<T> array, IComparer<T>? comparer)
{
Sort(array, 0, array.Length, comparer);
}
public static void Sort<T>(SegmentedArray<T> array, int index, int length, IComparer<T>? comparer)
{
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (length > 1)
{
var segment = new SegmentedArraySegment<T>(array, index, length);
SegmentedArraySortHelper<T>.Sort(segment, comparer);
}
}
public static void Sort<T>(SegmentedArray<T> array, Comparison<T> comparison)
{
if (comparison is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
if (array.Length > 1)
{
var segment = new SegmentedArraySegment<T>(array, 0, array.Length);
SegmentedArraySortHelper<T>.Sort(segment, comparison);
}
}
private static SegmentEnumerable<T> GetSegments<T>(this SegmentedArray<T> array, int offset, int length)
=> new(array, offset, length);
private static AlignedSegmentEnumerable<T> GetSegments<T>(SegmentedArray<T> first, SegmentedArray<T> second, int length)
=> new(first, second, length);
#pragma warning disable IDE0051 // Remove unused private members (will be used in follow-up)
private static AlignedSegmentEnumerable<T> GetSegmentsAligned<T>(SegmentedArray<T> first, int firstOffset, SegmentedArray<T> second, int secondOffset, int length)
=> new(first, firstOffset, second, secondOffset, length);
#pragma warning restore IDE0051 // Remove unused private members
private static UnalignedSegmentEnumerable<T> GetSegmentsUnaligned<T>(SegmentedArray<T> first, int firstOffset, SegmentedArray<T> second, int secondOffset, int length)
=> new(first, firstOffset, second, secondOffset, length);
private readonly struct AlignedSegmentEnumerable<T>
{
private readonly SegmentedArray<T> _first;
private readonly int _firstOffset;
private readonly SegmentedArray<T> _second;
private readonly int _secondOffset;
private readonly int _length;
public AlignedSegmentEnumerable(SegmentedArray<T> first, SegmentedArray<T> second, int length)
: this(first, 0, second, 0, length)
{
}
public AlignedSegmentEnumerable(SegmentedArray<T> first, int firstOffset, SegmentedArray<T> second, int secondOffset, int length)
{
_first = first;
_firstOffset = firstOffset;
_second = second;
_secondOffset = secondOffset;
_length = length;
}
public AlignedSegmentEnumerator<T> GetEnumerator()
=> new((T[][])_first.SyncRoot, _firstOffset, (T[][])_second.SyncRoot, _secondOffset, _length);
}
private struct AlignedSegmentEnumerator<T>
{
private readonly T[][] _firstSegments;
private readonly int _firstOffset;
private readonly T[][] _secondSegments;
private readonly int _secondOffset;
private readonly int _length;
private int _completed;
private (Memory<T> first, Memory<T> second) _current;
public AlignedSegmentEnumerator(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length)
{
_firstSegments = firstSegments;
_firstOffset = firstOffset;
_secondSegments = secondSegments;
_secondOffset = secondOffset;
_length = length;
_completed = 0;
_current = (Memory<T>.Empty, Memory<T>.Empty);
}
public (Memory<T> first, Memory<T> second) Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = (Memory<T>.Empty, Memory<T>.Empty);
return false;
}
if (_completed == 0)
{
var initialFirstSegment = _firstOffset >> SegmentedArrayHelper.GetSegmentShift<T>();
var initialSecondSegment = _secondOffset >> SegmentedArrayHelper.GetSegmentShift<T>();
var offset = _firstOffset & SegmentedArrayHelper.GetOffsetMask<T>();
Debug.Assert(offset == (_secondOffset & SegmentedArrayHelper.GetOffsetMask<T>()), "Aligned views must start at the same segment offset");
var firstSegment = _firstSegments[initialFirstSegment];
var secondSegment = _secondSegments[initialSecondSegment];
var remainingInSegment = firstSegment.Length - offset;
var currentSegmentLength = Math.Min(remainingInSegment, _length);
_current = (firstSegment.AsMemory().Slice(offset, currentSegmentLength), secondSegment.AsMemory().Slice(offset, currentSegmentLength));
_completed = currentSegmentLength;
return true;
}
else
{
var firstSegment = _firstSegments[(_completed + _firstOffset) >> SegmentedArrayHelper.GetSegmentShift<T>()];
var secondSegment = _secondSegments[(_completed + _secondOffset) >> SegmentedArrayHelper.GetSegmentShift<T>()];
var currentSegmentLength = Math.Min(SegmentedArrayHelper.GetSegmentSize<T>(), _length - _completed);
_current = (firstSegment.AsMemory().Slice(0, currentSegmentLength), secondSegment.AsMemory().Slice(0, currentSegmentLength));
_completed += currentSegmentLength;
return true;
}
}
}
private readonly struct UnalignedSegmentEnumerable<T>
{
private readonly SegmentedArray<T> _first;
private readonly int _firstOffset;
private readonly SegmentedArray<T> _second;
private readonly int _secondOffset;
private readonly int _length;
public UnalignedSegmentEnumerable(SegmentedArray<T> first, SegmentedArray<T> second, int length)
: this(first, 0, second, 0, length)
{
}
public UnalignedSegmentEnumerable(SegmentedArray<T> first, int firstOffset, SegmentedArray<T> second, int secondOffset, int length)
{
_first = first;
_firstOffset = firstOffset;
_second = second;
_secondOffset = secondOffset;
_length = length;
}
public UnalignedSegmentEnumerator<T> GetEnumerator()
=> new((T[][])_first.SyncRoot, _firstOffset, (T[][])_second.SyncRoot, _secondOffset, _length);
public ReverseEnumerable Reverse()
=> new(this);
public readonly struct ReverseEnumerable
{
private readonly UnalignedSegmentEnumerable<T> _enumerable;
public ReverseEnumerable(UnalignedSegmentEnumerable<T> enumerable)
{
_enumerable = enumerable;
}
public UnalignedSegmentEnumerator<T>.Reverse GetEnumerator()
=> new((T[][])_enumerable._first.SyncRoot, _enumerable._firstOffset, (T[][])_enumerable._second.SyncRoot, _enumerable._secondOffset, _enumerable._length);
public UnalignedSegmentEnumerable<T> Reverse()
=> _enumerable;
}
}
private struct UnalignedSegmentEnumerator<T>
{
private readonly T[][] _firstSegments;
private readonly int _firstOffset;
private readonly T[][] _secondSegments;
private readonly int _secondOffset;
private readonly int _length;
private int _completed;
private (Memory<T> first, Memory<T> second) _current;
public UnalignedSegmentEnumerator(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length)
{
_firstSegments = firstSegments;
_firstOffset = firstOffset;
_secondSegments = secondSegments;
_secondOffset = secondOffset;
_length = length;
_completed = 0;
_current = (Memory<T>.Empty, Memory<T>.Empty);
}
public (Memory<T> first, Memory<T> second) Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = (Memory<T>.Empty, Memory<T>.Empty);
return false;
}
var initialFirstSegment = (_completed + _firstOffset) >> SegmentedArrayHelper.GetSegmentShift<T>();
var initialSecondSegment = (_completed + _secondOffset) >> SegmentedArrayHelper.GetSegmentShift<T>();
var firstOffset = (_completed + _firstOffset) & SegmentedArrayHelper.GetOffsetMask<T>();
var secondOffset = (_completed + _secondOffset) & SegmentedArrayHelper.GetOffsetMask<T>();
var firstSegment = _firstSegments[initialFirstSegment];
var secondSegment = _secondSegments[initialSecondSegment];
var remainingInFirstSegment = firstSegment.Length - firstOffset;
var remainingInSecondSegment = secondSegment.Length - secondOffset;
var currentSegmentLength = Math.Min(Math.Min(remainingInFirstSegment, remainingInSecondSegment), _length - _completed);
_current = (firstSegment.AsMemory().Slice(firstOffset, currentSegmentLength), secondSegment.AsMemory().Slice(secondOffset, currentSegmentLength));
_completed += currentSegmentLength;
return true;
}
public struct Reverse
{
private readonly T[][] _firstSegments;
private readonly int _firstOffset;
private readonly T[][] _secondSegments;
private readonly int _secondOffset;
private readonly int _length;
private int _completed;
private (Memory<T> first, Memory<T> second) _current;
public Reverse(T[][] firstSegments, int firstOffset, T[][] secondSegments, int secondOffset, int length)
{
_firstSegments = firstSegments;
_firstOffset = firstOffset;
_secondSegments = secondSegments;
_secondOffset = secondOffset;
_length = length;
_completed = 0;
_current = (Memory<T>.Empty, Memory<T>.Empty);
}
public (Memory<T> first, Memory<T> second) Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = (Memory<T>.Empty, Memory<T>.Empty);
return false;
}
var initialFirstSegment = (_firstOffset + _length - _completed - 1) >> SegmentedArrayHelper.GetSegmentShift<T>();
var initialSecondSegment = (_secondOffset + _length - _completed - 1) >> SegmentedArrayHelper.GetSegmentShift<T>();
var firstOffset = (_firstOffset + _length - _completed - 1) & SegmentedArrayHelper.GetOffsetMask<T>();
var secondOffset = (_secondOffset + _length - _completed - 1) & SegmentedArrayHelper.GetOffsetMask<T>();
var firstSegment = _firstSegments[initialFirstSegment];
var secondSegment = _secondSegments[initialSecondSegment];
var remainingInFirstSegment = firstOffset + 1;
var remainingInSecondSegment = secondOffset + 1;
var currentSegmentLength = Math.Min(Math.Min(remainingInFirstSegment, remainingInSecondSegment), _length - _completed);
_current = (firstSegment.AsMemory().Slice(firstOffset - currentSegmentLength + 1, currentSegmentLength), secondSegment.AsMemory().Slice(secondOffset - currentSegmentLength + 1, currentSegmentLength));
_completed += currentSegmentLength;
return true;
}
}
}
private readonly struct SegmentEnumerable<T>
{
private readonly SegmentedArray<T> _array;
private readonly int _offset;
private readonly int _length;
public SegmentEnumerable(SegmentedArray<T> array)
{
_array = array;
_offset = 0;
_length = array.Length;
}
public SegmentEnumerable(SegmentedArray<T> array, int offset, int length)
{
if (offset < 0 || length < 0 || (uint)(offset + length) > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
_array = array;
_offset = offset;
_length = length;
}
public SegmentEnumerator<T> GetEnumerator()
=> new((T[][])_array.SyncRoot, _offset, _length);
public ReverseEnumerable Reverse()
=> new(this);
public readonly struct ReverseEnumerable
{
private readonly SegmentEnumerable<T> _enumerable;
public ReverseEnumerable(SegmentEnumerable<T> enumerable)
{
_enumerable = enumerable;
}
public SegmentEnumerator<T>.Reverse GetEnumerator()
=> new((T[][])_enumerable._array.SyncRoot, _enumerable._offset, _enumerable._length);
public SegmentEnumerable<T> Reverse()
=> _enumerable;
}
}
private struct SegmentEnumerator<T>
{
private readonly T[][] _segments;
private readonly int _offset;
private readonly int _length;
private int _completed;
private Memory<T> _current;
public SegmentEnumerator(T[][] segments, int offset, int length)
{
_segments = segments;
_offset = offset;
_length = length;
_completed = 0;
_current = Memory<T>.Empty;
}
public Memory<T> Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = Memory<T>.Empty;
return false;
}
if (_completed == 0)
{
var firstSegment = _offset >> SegmentedArrayHelper.GetSegmentShift<T>();
var offset = _offset & SegmentedArrayHelper.GetOffsetMask<T>();
var segment = _segments[firstSegment];
var remainingInSegment = segment.Length - offset;
_current = segment.AsMemory().Slice(offset, Math.Min(remainingInSegment, _length));
_completed = _current.Length;
return true;
}
else
{
var segment = _segments[(_completed + _offset) >> SegmentedArrayHelper.GetSegmentShift<T>()];
_current = segment.AsMemory().Slice(0, Math.Min(SegmentedArrayHelper.GetSegmentSize<T>(), _length - _completed));
_completed += _current.Length;
return true;
}
}
public struct Reverse
{
private readonly T[][] _segments;
private readonly int _offset;
private readonly int _length;
private int _completed;
private Memory<T> _current;
public Reverse(T[][] segments, int offset, int length)
{
_segments = segments;
_offset = offset;
_length = length;
_completed = 0;
_current = Memory<T>.Empty;
}
public Memory<T> Current => _current;
public bool MoveNext()
{
if (_completed == _length)
{
_current = Memory<T>.Empty;
return false;
}
if (_completed == 0)
{
var firstSegment = _offset >> SegmentedArrayHelper.GetSegmentShift<T>();
var offset = _offset & SegmentedArrayHelper.GetOffsetMask<T>();
var segment = _segments[firstSegment];
var remainingInSegment = segment.Length - offset;
_current = segment.AsMemory().Slice(offset, Math.Min(remainingInSegment, _length));
_completed = _current.Length;
return true;
}
else
{
var segment = _segments[(_completed + _offset) >> SegmentedArrayHelper.GetSegmentShift<T>()];
_current = segment.AsMemory().Slice(0, Math.Min(SegmentedArrayHelper.GetSegmentSize<T>(), _length - _completed));
_completed += _current.Length;
return true;
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/Test/Resources/Core/SymbolsTests/MultiModule/mod3.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.
'vbc /t:module /vbruntime- Mod3.vb
Public Class Class3
Sub Goo()
Dim x = {1,2}
Dim y = x.Count()
End Sub
End Class
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'vbc /t:module /vbruntime- Mod3.vb
Public Class Class3
Sub Goo()
Dim x = {1,2}
Dim y = x.Count()
End Sub
End Class
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/Core/Portable/Common/SymbolDisplayPartKindTags.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
internal static class SymbolDisplayPartKindTags
{
public static string GetTag(SymbolDisplayPartKind kind)
=> kind switch
{
SymbolDisplayPartKind.AliasName => TextTags.Alias,
SymbolDisplayPartKind.AssemblyName => TextTags.Assembly,
SymbolDisplayPartKind.ClassName => TextTags.Class,
SymbolDisplayPartKind.DelegateName => TextTags.Delegate,
SymbolDisplayPartKind.EnumName => TextTags.Enum,
SymbolDisplayPartKind.ErrorTypeName => TextTags.ErrorType,
SymbolDisplayPartKind.EventName => TextTags.Event,
SymbolDisplayPartKind.FieldName => TextTags.Field,
SymbolDisplayPartKind.InterfaceName => TextTags.Interface,
SymbolDisplayPartKind.Keyword => TextTags.Keyword,
SymbolDisplayPartKind.LabelName => TextTags.Label,
SymbolDisplayPartKind.LineBreak => TextTags.LineBreak,
SymbolDisplayPartKind.NumericLiteral => TextTags.NumericLiteral,
SymbolDisplayPartKind.StringLiteral => TextTags.StringLiteral,
SymbolDisplayPartKind.LocalName => TextTags.Local,
SymbolDisplayPartKind.MethodName => TextTags.Method,
SymbolDisplayPartKind.ModuleName => TextTags.Module,
SymbolDisplayPartKind.NamespaceName => TextTags.Namespace,
SymbolDisplayPartKind.Operator => TextTags.Operator,
SymbolDisplayPartKind.ParameterName => TextTags.Parameter,
SymbolDisplayPartKind.PropertyName => TextTags.Property,
SymbolDisplayPartKind.Punctuation => TextTags.Punctuation,
SymbolDisplayPartKind.Space => TextTags.Space,
SymbolDisplayPartKind.StructName => TextTags.Struct,
SymbolDisplayPartKind.AnonymousTypeIndicator => TextTags.AnonymousTypeIndicator,
SymbolDisplayPartKind.Text => TextTags.Text,
SymbolDisplayPartKind.TypeParameterName => TextTags.TypeParameter,
SymbolDisplayPartKind.RangeVariableName => TextTags.RangeVariable,
SymbolDisplayPartKind.EnumMemberName => TextTags.EnumMember,
SymbolDisplayPartKind.ExtensionMethodName => TextTags.ExtensionMethod,
SymbolDisplayPartKind.ConstantName => TextTags.Constant,
SymbolDisplayPartKind.RecordClassName => TextTags.Record,
SymbolDisplayPartKind.RecordStructName => TextTags.RecordStruct,
_ => string.Empty,
};
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis
{
internal static class SymbolDisplayPartKindTags
{
public static string GetTag(SymbolDisplayPartKind kind)
=> kind switch
{
SymbolDisplayPartKind.AliasName => TextTags.Alias,
SymbolDisplayPartKind.AssemblyName => TextTags.Assembly,
SymbolDisplayPartKind.ClassName => TextTags.Class,
SymbolDisplayPartKind.DelegateName => TextTags.Delegate,
SymbolDisplayPartKind.EnumName => TextTags.Enum,
SymbolDisplayPartKind.ErrorTypeName => TextTags.ErrorType,
SymbolDisplayPartKind.EventName => TextTags.Event,
SymbolDisplayPartKind.FieldName => TextTags.Field,
SymbolDisplayPartKind.InterfaceName => TextTags.Interface,
SymbolDisplayPartKind.Keyword => TextTags.Keyword,
SymbolDisplayPartKind.LabelName => TextTags.Label,
SymbolDisplayPartKind.LineBreak => TextTags.LineBreak,
SymbolDisplayPartKind.NumericLiteral => TextTags.NumericLiteral,
SymbolDisplayPartKind.StringLiteral => TextTags.StringLiteral,
SymbolDisplayPartKind.LocalName => TextTags.Local,
SymbolDisplayPartKind.MethodName => TextTags.Method,
SymbolDisplayPartKind.ModuleName => TextTags.Module,
SymbolDisplayPartKind.NamespaceName => TextTags.Namespace,
SymbolDisplayPartKind.Operator => TextTags.Operator,
SymbolDisplayPartKind.ParameterName => TextTags.Parameter,
SymbolDisplayPartKind.PropertyName => TextTags.Property,
SymbolDisplayPartKind.Punctuation => TextTags.Punctuation,
SymbolDisplayPartKind.Space => TextTags.Space,
SymbolDisplayPartKind.StructName => TextTags.Struct,
SymbolDisplayPartKind.AnonymousTypeIndicator => TextTags.AnonymousTypeIndicator,
SymbolDisplayPartKind.Text => TextTags.Text,
SymbolDisplayPartKind.TypeParameterName => TextTags.TypeParameter,
SymbolDisplayPartKind.RangeVariableName => TextTags.RangeVariable,
SymbolDisplayPartKind.EnumMemberName => TextTags.EnumMember,
SymbolDisplayPartKind.ExtensionMethodName => TextTags.ExtensionMethod,
SymbolDisplayPartKind.ConstantName => TextTags.Constant,
SymbolDisplayPartKind.RecordClassName => TextTags.Record,
SymbolDisplayPartKind.RecordStructName => TextTags.RecordStruct,
_ => string.Empty,
};
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/CSharp/Portable/Symbols/SubstitutedPropertySymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SubstitutedPropertySymbol : WrappedPropertySymbol
{
private readonly SubstitutedNamedTypeSymbol _containingType;
private TypeWithAnnotations.Boxed _lazyType;
private ImmutableArray<ParameterSymbol> _lazyParameters;
internal SubstitutedPropertySymbol(SubstitutedNamedTypeSymbol containingType, PropertySymbol originalDefinition)
: base(originalDefinition)
{
_containingType = containingType;
}
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
if (_lazyType == null)
{
var type = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.TypeWithAnnotations);
Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null);
}
return _lazyType.Value;
}
}
public override Symbol ContainingSymbol
{
get
{
return _containingType;
}
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType;
}
}
public override PropertySymbol OriginalDefinition
{
get
{
return _underlyingProperty;
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return OriginalDefinition.GetAttributes();
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _containingType.TypeSubstitution.SubstituteCustomModifiers(OriginalDefinition.RefCustomModifiers); }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get
{
if (_lazyParameters.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyParameters, SubstituteParameters(), default(ImmutableArray<ParameterSymbol>));
}
return _lazyParameters;
}
}
public override MethodSymbol GetMethod
{
get
{
MethodSymbol originalGetMethod = OriginalDefinition.GetMethod;
return (object)originalGetMethod == null ? null : originalGetMethod.AsMember(_containingType);
}
}
public override MethodSymbol SetMethod
{
get
{
MethodSymbol originalSetMethod = OriginalDefinition.SetMethod;
return (object)originalSetMethod == null ? null : originalSetMethod.AsMember(_containingType);
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return OriginalDefinition.IsExplicitInterfaceImplementation; }
}
//we want to compute this lazily since it may be expensive for the underlying symbol
private ImmutableArray<PropertySymbol> _lazyExplicitInterfaceImplementations;
private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers;
public override ImmutableArray<PropertySymbol> ExplicitInterfaceImplementations
{
get
{
if (_lazyExplicitInterfaceImplementations.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(
ref _lazyExplicitInterfaceImplementations,
ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution),
default(ImmutableArray<PropertySymbol>));
}
return _lazyExplicitInterfaceImplementations;
}
}
internal override bool MustCallMethodsDirectly
{
get { return OriginalDefinition.MustCallMethodsDirectly; }
}
internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers
{
get
{
if (_lazyOverriddenOrHiddenMembers == null)
{
Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null);
}
return _lazyOverriddenOrHiddenMembers;
}
}
private ImmutableArray<ParameterSymbol> SubstituteParameters()
{
var unsubstitutedParameters = OriginalDefinition.Parameters;
if (unsubstitutedParameters.IsEmpty)
{
return unsubstitutedParameters;
}
else
{
int count = unsubstitutedParameters.Length;
var substituted = new ParameterSymbol[count];
for (int i = 0; i < count; i++)
{
substituted[i] = new SubstitutedParameterSymbol(this, _containingType.TypeSubstitution, unsubstitutedParameters[i]);
}
return substituted.AsImmutableOrNull();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SubstitutedPropertySymbol : WrappedPropertySymbol
{
private readonly SubstitutedNamedTypeSymbol _containingType;
private TypeWithAnnotations.Boxed _lazyType;
private ImmutableArray<ParameterSymbol> _lazyParameters;
internal SubstitutedPropertySymbol(SubstitutedNamedTypeSymbol containingType, PropertySymbol originalDefinition)
: base(originalDefinition)
{
_containingType = containingType;
}
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
if (_lazyType == null)
{
var type = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.TypeWithAnnotations);
Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null);
}
return _lazyType.Value;
}
}
public override Symbol ContainingSymbol
{
get
{
return _containingType;
}
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType;
}
}
public override PropertySymbol OriginalDefinition
{
get
{
return _underlyingProperty;
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return OriginalDefinition.GetAttributes();
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _containingType.TypeSubstitution.SubstituteCustomModifiers(OriginalDefinition.RefCustomModifiers); }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get
{
if (_lazyParameters.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyParameters, SubstituteParameters(), default(ImmutableArray<ParameterSymbol>));
}
return _lazyParameters;
}
}
public override MethodSymbol GetMethod
{
get
{
MethodSymbol originalGetMethod = OriginalDefinition.GetMethod;
return (object)originalGetMethod == null ? null : originalGetMethod.AsMember(_containingType);
}
}
public override MethodSymbol SetMethod
{
get
{
MethodSymbol originalSetMethod = OriginalDefinition.SetMethod;
return (object)originalSetMethod == null ? null : originalSetMethod.AsMember(_containingType);
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return OriginalDefinition.IsExplicitInterfaceImplementation; }
}
//we want to compute this lazily since it may be expensive for the underlying symbol
private ImmutableArray<PropertySymbol> _lazyExplicitInterfaceImplementations;
private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers;
public override ImmutableArray<PropertySymbol> ExplicitInterfaceImplementations
{
get
{
if (_lazyExplicitInterfaceImplementations.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(
ref _lazyExplicitInterfaceImplementations,
ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution),
default(ImmutableArray<PropertySymbol>));
}
return _lazyExplicitInterfaceImplementations;
}
}
internal override bool MustCallMethodsDirectly
{
get { return OriginalDefinition.MustCallMethodsDirectly; }
}
internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers
{
get
{
if (_lazyOverriddenOrHiddenMembers == null)
{
Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null);
}
return _lazyOverriddenOrHiddenMembers;
}
}
private ImmutableArray<ParameterSymbol> SubstituteParameters()
{
var unsubstitutedParameters = OriginalDefinition.Parameters;
if (unsubstitutedParameters.IsEmpty)
{
return unsubstitutedParameters;
}
else
{
int count = unsubstitutedParameters.Length;
var substituted = new ParameterSymbol[count];
for (int i = 0; i < count; i++)
{
substituted[i] = new SubstitutedParameterSymbol(this, _containingType.TypeSubstitution, unsubstitutedParameters[i]);
}
return substituted.AsImmutableOrNull();
}
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/Core/Portable/Syntax/SyntaxNavigator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class SyntaxNavigator
{
private const int None = 0;
public static readonly SyntaxNavigator Instance = new SyntaxNavigator();
private SyntaxNavigator()
{
}
[Flags]
private enum SyntaxKinds
{
DocComments = 1,
Directives = 2,
SkippedTokens = 4,
}
private static readonly Func<SyntaxTrivia, bool>?[] s_stepIntoFunctions = new Func<SyntaxTrivia, bool>?[]
{
/* 000 */ null,
/* 001 */ t => t.IsDocumentationCommentTrivia,
/* 010 */ t => t.IsDirective,
/* 011 */ t => t.IsDirective || t.IsDocumentationCommentTrivia,
/* 100 */ t => t.IsSkippedTokensTrivia,
/* 101 */ t => t.IsSkippedTokensTrivia || t.IsDocumentationCommentTrivia,
/* 110 */ t => t.IsSkippedTokensTrivia || t.IsDirective,
/* 111 */ t => t.IsSkippedTokensTrivia || t.IsDirective || t.IsDocumentationCommentTrivia,
};
private static Func<SyntaxTrivia, bool>? GetStepIntoFunction(
bool skipped, bool directives, bool docComments)
{
var index = (skipped ? SyntaxKinds.SkippedTokens : 0) |
(directives ? SyntaxKinds.Directives : 0) |
(docComments ? SyntaxKinds.DocComments : 0);
return s_stepIntoFunctions[(int)index];
}
private static Func<SyntaxToken, bool> GetPredicateFunction(bool includeZeroWidth)
{
return includeZeroWidth ? SyntaxToken.Any : SyntaxToken.NonZeroWidth;
}
private static bool Matches(Func<SyntaxToken, bool>? predicate, SyntaxToken token)
{
return predicate == null || ReferenceEquals(predicate, SyntaxToken.Any) || predicate(token);
}
internal SyntaxToken GetFirstToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetFirstToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetLastToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetLastToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetPreviousToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetNextToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetNextToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
return GetPreviousToken(current, predicate, stepInto != null, stepInto);
}
internal SyntaxToken GetNextToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
return GetNextToken(current, predicate, stepInto != null, stepInto);
}
private static readonly ObjectPool<Stack<ChildSyntaxList.Enumerator>> s_childEnumeratorStackPool
= new ObjectPool<Stack<ChildSyntaxList.Enumerator>>(() => new Stack<ChildSyntaxList.Enumerator>(), 10);
internal SyntaxToken GetFirstToken(SyntaxNode current, Func<SyntaxToken, bool>? predicate, Func<SyntaxTrivia, bool>? stepInto)
{
var stack = s_childEnumeratorStackPool.Allocate();
try
{
stack.Push(current.ChildNodesAndTokens().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Pop();
if (en.MoveNext())
{
var child = en.Current;
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
// push this enumerator back, not done yet
stack.Push(en);
if (child.IsNode)
{
Debug.Assert(child.IsNode);
stack.Push(child.AsNode()!.ChildNodesAndTokens().GetEnumerator());
}
}
}
return default;
}
finally
{
stack.Clear();
s_childEnumeratorStackPool.Free(stack);
}
}
private static readonly ObjectPool<Stack<ChildSyntaxList.Reversed.Enumerator>> s_childReversedEnumeratorStackPool
= new ObjectPool<Stack<ChildSyntaxList.Reversed.Enumerator>>(() => new Stack<ChildSyntaxList.Reversed.Enumerator>(), 10);
internal SyntaxToken GetLastToken(SyntaxNode current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
var stack = s_childReversedEnumeratorStackPool.Allocate();
try
{
stack.Push(current.ChildNodesAndTokens().Reverse().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Pop();
if (en.MoveNext())
{
var child = en.Current;
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
// push this enumerator back, not done yet
stack.Push(en);
if (child.IsNode)
{
Debug.Assert(child.IsNode);
stack.Push(child.AsNode()!.ChildNodesAndTokens().Reverse().GetEnumerator());
}
}
}
return default;
}
finally
{
stack.Clear();
s_childReversedEnumeratorStackPool.Free(stack);
}
}
private SyntaxToken GetFirstToken(
SyntaxTriviaList triviaList,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool> stepInto)
{
Debug.Assert(stepInto != null);
foreach (var trivia in triviaList)
{
if (trivia.TryGetStructure(out var structure) && stepInto(trivia))
{
var token = GetFirstToken(structure, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
return default;
}
private SyntaxToken GetLastToken(
SyntaxTriviaList list,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool> stepInto)
{
Debug.Assert(stepInto != null);
foreach (var trivia in list.Reverse())
{
SyntaxToken token;
if (TryGetLastTokenForStructuredTrivia(trivia, predicate, stepInto, out token))
{
return token;
}
}
return default;
}
private bool TryGetLastTokenForStructuredTrivia(
SyntaxTrivia trivia,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto,
out SyntaxToken token)
{
token = default;
if (!trivia.TryGetStructure(out var structure) || stepInto == null || !stepInto(trivia))
{
return false;
}
token = GetLastToken(structure, predicate, stepInto);
return token.RawKind != None;
}
private SyntaxToken GetFirstToken(
SyntaxToken token,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
// find first token that matches (either specified token or token inside related trivia)
if (stepInto != null)
{
// search in leading trivia
var firstToken = GetFirstToken(token.LeadingTrivia, predicate, stepInto);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
if (Matches(predicate, token))
{
return token;
}
if (stepInto != null)
{
// search in trailing trivia
var firstToken = GetFirstToken(token.TrailingTrivia, predicate, stepInto);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
return default;
}
private SyntaxToken GetLastToken(
SyntaxToken token,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
// find first token that matches (either specified token or token inside related trivia)
if (stepInto != null)
{
// search in leading trivia
var lastToken = GetLastToken(token.TrailingTrivia, predicate, stepInto);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
if (Matches(predicate, token))
{
return token;
}
if (stepInto != null)
{
// search in trailing trivia
var lastToken = GetLastToken(token.LeadingTrivia, predicate, stepInto);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
return default;
}
internal SyntaxToken GetNextToken(
SyntaxTrivia current,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
bool returnNext = false;
// look inside leading trivia for current & next
var token = GetNextToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnNext);
if (token.RawKind != None)
{
return token;
}
// consider containing token if current trivia was in the leading trivia
if (returnNext && (predicate == null || predicate == SyntaxToken.Any || predicate(current.Token)))
{
return current.Token;
}
// look inside trailing trivia for current & next (or just next)
token = GetNextToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnNext);
if (token.RawKind != None)
{
return token;
}
// did not find next inside trivia, try next sibling token
// (don't look in trailing trivia of token since it was already searched above)
return GetNextToken(current.Token, predicate, false, stepInto);
}
internal SyntaxToken GetPreviousToken(
SyntaxTrivia current,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
bool returnPrevious = false;
// look inside leading trivia for current & next
var token = GetPreviousToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnPrevious);
if (token.RawKind != None)
{
return token;
}
// consider containing token if current trivia was in the leading trivia
if (returnPrevious && Matches(predicate, current.Token))
{
return current.Token;
}
// look inside trailing trivia for current & next (or just next)
token = GetPreviousToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnPrevious);
if (token.RawKind != None)
{
return token;
}
// did not find next inside trivia, try next sibling token
// (don't look in trailing trivia of token since it was already searched above)
return GetPreviousToken(current.Token, predicate, false, stepInto);
}
private SyntaxToken GetNextToken(
SyntaxTrivia current,
SyntaxTriviaList list,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto,
ref bool returnNext)
{
foreach (var trivia in list)
{
if (returnNext)
{
if (trivia.TryGetStructure(out var structure) && stepInto != null && stepInto(trivia))
{
var token = GetFirstToken(structure!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (trivia == current)
{
returnNext = true;
}
}
return default;
}
private SyntaxToken GetPreviousToken(
SyntaxTrivia current,
SyntaxTriviaList list,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto,
ref bool returnPrevious)
{
foreach (var trivia in list.Reverse())
{
if (returnPrevious)
{
SyntaxToken token;
if (TryGetLastTokenForStructuredTrivia(trivia, predicate, stepInto, out token))
{
return token;
}
}
else if (trivia == current)
{
returnPrevious = true;
}
}
return default;
}
internal SyntaxToken GetNextToken(
SyntaxNode node,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
while (node.Parent != null)
{
// walk forward in parent's child list until we find ourselves and then return the
// next token
bool returnNext = false;
foreach (var child in node.Parent.ChildNodesAndTokens())
{
if (returnNext)
{
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetFirstToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsNode && child.AsNode() == node)
{
returnNext = true;
}
}
// didn't find the next token in my parent's children, look up the tree
node = node.Parent;
}
if (node.IsStructuredTrivia)
{
return GetNextToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetPreviousToken(
SyntaxNode node,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
while (node.Parent != null)
{
// walk forward in parent's child list until we find ourselves and then return the
// previous token
bool returnPrevious = false;
foreach (var child in node.Parent.ChildNodesAndTokens().Reverse())
{
if (returnPrevious)
{
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetLastToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsNode && child.AsNode() == node)
{
returnPrevious = true;
}
}
// didn't find the previous token in my parent's children, look up the tree
node = node.Parent;
}
if (node.IsStructuredTrivia)
{
return GetPreviousToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetNextToken(in SyntaxToken current, Func<SyntaxToken, bool>? predicate, bool searchInsideCurrentTokenTrailingTrivia, Func<SyntaxTrivia, bool>? stepInto)
{
Debug.Assert(searchInsideCurrentTokenTrailingTrivia == false || stepInto != null);
if (current.Parent != null)
{
// look inside trailing trivia for structure
if (searchInsideCurrentTokenTrailingTrivia)
{
var firstToken = GetFirstToken(current.TrailingTrivia, predicate, stepInto!);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
// walk forward in parent's child list until we find ourself
// and then return the next token
bool returnNext = false;
foreach (var child in current.Parent.ChildNodesAndTokens())
{
if (returnNext)
{
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetFirstToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsToken && child.AsToken() == current)
{
returnNext = true;
}
}
// otherwise get next token from the parent's parent, and so on
return GetNextToken(current.Parent, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, bool searchInsideCurrentTokenLeadingTrivia,
Func<SyntaxTrivia, bool>? stepInto)
{
Debug.Assert(searchInsideCurrentTokenLeadingTrivia == false || stepInto != null);
if (current.Parent != null)
{
// look inside trailing trivia for structure
if (searchInsideCurrentTokenLeadingTrivia)
{
var lastToken = GetLastToken(current.LeadingTrivia, predicate, stepInto!);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
// walk forward in parent's child list until we find ourself
// and then return the next token
bool returnPrevious = false;
foreach (var child in current.Parent.ChildNodesAndTokens().Reverse())
{
if (returnPrevious)
{
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetLastToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsToken && child.AsToken() == current)
{
returnPrevious = true;
}
}
// otherwise get next token from the parent's parent, and so on
return GetPreviousToken(current.Parent, predicate, stepInto);
}
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;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class SyntaxNavigator
{
private const int None = 0;
public static readonly SyntaxNavigator Instance = new SyntaxNavigator();
private SyntaxNavigator()
{
}
[Flags]
private enum SyntaxKinds
{
DocComments = 1,
Directives = 2,
SkippedTokens = 4,
}
private static readonly Func<SyntaxTrivia, bool>?[] s_stepIntoFunctions = new Func<SyntaxTrivia, bool>?[]
{
/* 000 */ null,
/* 001 */ t => t.IsDocumentationCommentTrivia,
/* 010 */ t => t.IsDirective,
/* 011 */ t => t.IsDirective || t.IsDocumentationCommentTrivia,
/* 100 */ t => t.IsSkippedTokensTrivia,
/* 101 */ t => t.IsSkippedTokensTrivia || t.IsDocumentationCommentTrivia,
/* 110 */ t => t.IsSkippedTokensTrivia || t.IsDirective,
/* 111 */ t => t.IsSkippedTokensTrivia || t.IsDirective || t.IsDocumentationCommentTrivia,
};
private static Func<SyntaxTrivia, bool>? GetStepIntoFunction(
bool skipped, bool directives, bool docComments)
{
var index = (skipped ? SyntaxKinds.SkippedTokens : 0) |
(directives ? SyntaxKinds.Directives : 0) |
(docComments ? SyntaxKinds.DocComments : 0);
return s_stepIntoFunctions[(int)index];
}
private static Func<SyntaxToken, bool> GetPredicateFunction(bool includeZeroWidth)
{
return includeZeroWidth ? SyntaxToken.Any : SyntaxToken.NonZeroWidth;
}
private static bool Matches(Func<SyntaxToken, bool>? predicate, SyntaxToken token)
{
return predicate == null || ReferenceEquals(predicate, SyntaxToken.Any) || predicate(token);
}
internal SyntaxToken GetFirstToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetFirstToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetLastToken(in SyntaxNode current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetLastToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetPreviousToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetNextToken(in SyntaxToken current, bool includeZeroWidth, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return GetNextToken(current, GetPredicateFunction(includeZeroWidth), GetStepIntoFunction(includeSkipped, includeDirectives, includeDocumentationComments));
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
return GetPreviousToken(current, predicate, stepInto != null, stepInto);
}
internal SyntaxToken GetNextToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
return GetNextToken(current, predicate, stepInto != null, stepInto);
}
private static readonly ObjectPool<Stack<ChildSyntaxList.Enumerator>> s_childEnumeratorStackPool
= new ObjectPool<Stack<ChildSyntaxList.Enumerator>>(() => new Stack<ChildSyntaxList.Enumerator>(), 10);
internal SyntaxToken GetFirstToken(SyntaxNode current, Func<SyntaxToken, bool>? predicate, Func<SyntaxTrivia, bool>? stepInto)
{
var stack = s_childEnumeratorStackPool.Allocate();
try
{
stack.Push(current.ChildNodesAndTokens().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Pop();
if (en.MoveNext())
{
var child = en.Current;
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
// push this enumerator back, not done yet
stack.Push(en);
if (child.IsNode)
{
Debug.Assert(child.IsNode);
stack.Push(child.AsNode()!.ChildNodesAndTokens().GetEnumerator());
}
}
}
return default;
}
finally
{
stack.Clear();
s_childEnumeratorStackPool.Free(stack);
}
}
private static readonly ObjectPool<Stack<ChildSyntaxList.Reversed.Enumerator>> s_childReversedEnumeratorStackPool
= new ObjectPool<Stack<ChildSyntaxList.Reversed.Enumerator>>(() => new Stack<ChildSyntaxList.Reversed.Enumerator>(), 10);
internal SyntaxToken GetLastToken(SyntaxNode current, Func<SyntaxToken, bool> predicate, Func<SyntaxTrivia, bool>? stepInto)
{
var stack = s_childReversedEnumeratorStackPool.Allocate();
try
{
stack.Push(current.ChildNodesAndTokens().Reverse().GetEnumerator());
while (stack.Count > 0)
{
var en = stack.Pop();
if (en.MoveNext())
{
var child = en.Current;
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
// push this enumerator back, not done yet
stack.Push(en);
if (child.IsNode)
{
Debug.Assert(child.IsNode);
stack.Push(child.AsNode()!.ChildNodesAndTokens().Reverse().GetEnumerator());
}
}
}
return default;
}
finally
{
stack.Clear();
s_childReversedEnumeratorStackPool.Free(stack);
}
}
private SyntaxToken GetFirstToken(
SyntaxTriviaList triviaList,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool> stepInto)
{
Debug.Assert(stepInto != null);
foreach (var trivia in triviaList)
{
if (trivia.TryGetStructure(out var structure) && stepInto(trivia))
{
var token = GetFirstToken(structure, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
return default;
}
private SyntaxToken GetLastToken(
SyntaxTriviaList list,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool> stepInto)
{
Debug.Assert(stepInto != null);
foreach (var trivia in list.Reverse())
{
SyntaxToken token;
if (TryGetLastTokenForStructuredTrivia(trivia, predicate, stepInto, out token))
{
return token;
}
}
return default;
}
private bool TryGetLastTokenForStructuredTrivia(
SyntaxTrivia trivia,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto,
out SyntaxToken token)
{
token = default;
if (!trivia.TryGetStructure(out var structure) || stepInto == null || !stepInto(trivia))
{
return false;
}
token = GetLastToken(structure, predicate, stepInto);
return token.RawKind != None;
}
private SyntaxToken GetFirstToken(
SyntaxToken token,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
// find first token that matches (either specified token or token inside related trivia)
if (stepInto != null)
{
// search in leading trivia
var firstToken = GetFirstToken(token.LeadingTrivia, predicate, stepInto);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
if (Matches(predicate, token))
{
return token;
}
if (stepInto != null)
{
// search in trailing trivia
var firstToken = GetFirstToken(token.TrailingTrivia, predicate, stepInto);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
return default;
}
private SyntaxToken GetLastToken(
SyntaxToken token,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
// find first token that matches (either specified token or token inside related trivia)
if (stepInto != null)
{
// search in leading trivia
var lastToken = GetLastToken(token.TrailingTrivia, predicate, stepInto);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
if (Matches(predicate, token))
{
return token;
}
if (stepInto != null)
{
// search in trailing trivia
var lastToken = GetLastToken(token.LeadingTrivia, predicate, stepInto);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
return default;
}
internal SyntaxToken GetNextToken(
SyntaxTrivia current,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
bool returnNext = false;
// look inside leading trivia for current & next
var token = GetNextToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnNext);
if (token.RawKind != None)
{
return token;
}
// consider containing token if current trivia was in the leading trivia
if (returnNext && (predicate == null || predicate == SyntaxToken.Any || predicate(current.Token)))
{
return current.Token;
}
// look inside trailing trivia for current & next (or just next)
token = GetNextToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnNext);
if (token.RawKind != None)
{
return token;
}
// did not find next inside trivia, try next sibling token
// (don't look in trailing trivia of token since it was already searched above)
return GetNextToken(current.Token, predicate, false, stepInto);
}
internal SyntaxToken GetPreviousToken(
SyntaxTrivia current,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
bool returnPrevious = false;
// look inside leading trivia for current & next
var token = GetPreviousToken(current, current.Token.TrailingTrivia, predicate, stepInto, ref returnPrevious);
if (token.RawKind != None)
{
return token;
}
// consider containing token if current trivia was in the leading trivia
if (returnPrevious && Matches(predicate, current.Token))
{
return current.Token;
}
// look inside trailing trivia for current & next (or just next)
token = GetPreviousToken(current, current.Token.LeadingTrivia, predicate, stepInto, ref returnPrevious);
if (token.RawKind != None)
{
return token;
}
// did not find next inside trivia, try next sibling token
// (don't look in trailing trivia of token since it was already searched above)
return GetPreviousToken(current.Token, predicate, false, stepInto);
}
private SyntaxToken GetNextToken(
SyntaxTrivia current,
SyntaxTriviaList list,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto,
ref bool returnNext)
{
foreach (var trivia in list)
{
if (returnNext)
{
if (trivia.TryGetStructure(out var structure) && stepInto != null && stepInto(trivia))
{
var token = GetFirstToken(structure!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (trivia == current)
{
returnNext = true;
}
}
return default;
}
private SyntaxToken GetPreviousToken(
SyntaxTrivia current,
SyntaxTriviaList list,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto,
ref bool returnPrevious)
{
foreach (var trivia in list.Reverse())
{
if (returnPrevious)
{
SyntaxToken token;
if (TryGetLastTokenForStructuredTrivia(trivia, predicate, stepInto, out token))
{
return token;
}
}
else if (trivia == current)
{
returnPrevious = true;
}
}
return default;
}
internal SyntaxToken GetNextToken(
SyntaxNode node,
Func<SyntaxToken, bool>? predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
while (node.Parent != null)
{
// walk forward in parent's child list until we find ourselves and then return the
// next token
bool returnNext = false;
foreach (var child in node.Parent.ChildNodesAndTokens())
{
if (returnNext)
{
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetFirstToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsNode && child.AsNode() == node)
{
returnNext = true;
}
}
// didn't find the next token in my parent's children, look up the tree
node = node.Parent;
}
if (node.IsStructuredTrivia)
{
return GetNextToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetPreviousToken(
SyntaxNode node,
Func<SyntaxToken, bool> predicate,
Func<SyntaxTrivia, bool>? stepInto)
{
while (node.Parent != null)
{
// walk forward in parent's child list until we find ourselves and then return the
// previous token
bool returnPrevious = false;
foreach (var child in node.Parent.ChildNodesAndTokens().Reverse())
{
if (returnPrevious)
{
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetLastToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsNode && child.AsNode() == node)
{
returnPrevious = true;
}
}
// didn't find the previous token in my parent's children, look up the tree
node = node.Parent;
}
if (node.IsStructuredTrivia)
{
return GetPreviousToken(((IStructuredTriviaSyntax)node).ParentTrivia, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetNextToken(in SyntaxToken current, Func<SyntaxToken, bool>? predicate, bool searchInsideCurrentTokenTrailingTrivia, Func<SyntaxTrivia, bool>? stepInto)
{
Debug.Assert(searchInsideCurrentTokenTrailingTrivia == false || stepInto != null);
if (current.Parent != null)
{
// look inside trailing trivia for structure
if (searchInsideCurrentTokenTrailingTrivia)
{
var firstToken = GetFirstToken(current.TrailingTrivia, predicate, stepInto!);
if (firstToken.RawKind != None)
{
return firstToken;
}
}
// walk forward in parent's child list until we find ourself
// and then return the next token
bool returnNext = false;
foreach (var child in current.Parent.ChildNodesAndTokens())
{
if (returnNext)
{
if (child.IsToken)
{
var token = GetFirstToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetFirstToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsToken && child.AsToken() == current)
{
returnNext = true;
}
}
// otherwise get next token from the parent's parent, and so on
return GetNextToken(current.Parent, predicate, stepInto);
}
return default;
}
internal SyntaxToken GetPreviousToken(in SyntaxToken current, Func<SyntaxToken, bool> predicate, bool searchInsideCurrentTokenLeadingTrivia,
Func<SyntaxTrivia, bool>? stepInto)
{
Debug.Assert(searchInsideCurrentTokenLeadingTrivia == false || stepInto != null);
if (current.Parent != null)
{
// look inside trailing trivia for structure
if (searchInsideCurrentTokenLeadingTrivia)
{
var lastToken = GetLastToken(current.LeadingTrivia, predicate, stepInto!);
if (lastToken.RawKind != None)
{
return lastToken;
}
}
// walk forward in parent's child list until we find ourself
// and then return the next token
bool returnPrevious = false;
foreach (var child in current.Parent.ChildNodesAndTokens().Reverse())
{
if (returnPrevious)
{
if (child.IsToken)
{
var token = GetLastToken(child.AsToken(), predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
else
{
Debug.Assert(child.IsNode);
var token = GetLastToken(child.AsNode()!, predicate, stepInto);
if (token.RawKind != None)
{
return token;
}
}
}
else if (child.IsToken && child.AsToken() == current)
{
returnPrevious = true;
}
}
// otherwise get next token from the parent's parent, and so on
return GetPreviousToken(current.Parent, predicate, stepInto);
}
return default;
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/VisualStudio/Core/Test/CodeModel/AbstractCodeParameterTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Public MustInherit Class AbstractCodeParameterTests
Inherits AbstractCodeElementTests(Of EnvDTE80.CodeParameter2)
Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeParameter2) As String
Throw New NotImplementedException()
End Function
Protected Function GetDefaultValueSetter(codeElement As EnvDTE80.CodeParameter2) As Action(Of String)
Return Sub(defaultValue) codeElement.DefaultValue = defaultValue
End Function
Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeParameter2) As String
Throw New NotImplementedException()
End Function
Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeParameter2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetEndPoint(part)
End Function
Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeParameter2) As String
Return codeElement.FullName
End Function
Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeParameter2) As EnvDTE.vsCMElement
Return codeElement.Kind
End Function
Protected Overrides Function GetName(codeElement As EnvDTE80.CodeParameter2) As String
Return codeElement.Name
End Function
Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeParameter2) As Action(Of String)
Throw New NotImplementedException()
End Function
Protected Function GetParameterKindSetter(codeElement As EnvDTE80.CodeParameter2) As Action(Of EnvDTE80.vsCMParameterKind)
Return Sub(kind) codeElement.ParameterKind = kind
End Function
Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeParameter2) As Object
Return codeElement.Parent
End Function
Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeParameter2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetStartPoint(part)
End Function
Protected Overrides Function GetTypeProp(codeElement As EnvDTE80.CodeParameter2) As EnvDTE.CodeTypeRef
Return codeElement.Type
End Function
Protected Overrides Function GetTypePropSetter(codeElement As EnvDTE80.CodeParameter2) As Action(Of EnvDTE.CodeTypeRef)
Return Sub(value) codeElement.Type = value
End Function
Protected Overrides Function AddAttribute(codeElement As EnvDTE80.CodeParameter2, data As AttributeData) As EnvDTE.CodeAttribute
Return codeElement.AddAttribute(data.Name, data.Value, data.Position)
End Function
Protected Sub TestParameterKind(code As XElement, kind As EnvDTE80.vsCMParameterKind)
TestElement(code,
Sub(codeElement)
Assert.Equal(kind, codeElement.ParameterKind)
End Sub)
End Sub
Protected Sub TestDefaultValue(code As XElement, expectedValue As String)
TestElement(code,
Sub(codeElement)
Assert.Equal(expectedValue, codeElement.DefaultValue)
End Sub)
End Sub
Protected Async Function TestSetParameterKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMParameterKind) As Task
Await TestSetParameterKind(code, expectedCode, kind, NoThrow(Of EnvDTE80.vsCMParameterKind)())
End Function
Protected Async Function TestSetParameterKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMParameterKind, action As SetterAction(Of EnvDTE80.vsCMParameterKind)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim parameterKindSetter = GetParameterKindSetter(codeElement)
action(kind, parameterKindSetter)
End Sub)
End Function
Protected Async Function TestSetDefaultValue(code As XElement, expected As XElement, defaultValue As String) As Task
Await TestSetDefaultValue(code, expected, defaultValue, NoThrow(Of String)())
End Function
Protected Async Function TestSetDefaultValue(code As XElement, expectedCode As XElement, defaultValue As String, action As SetterAction(Of String)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim defaultValueSetter = GetDefaultValueSetter(codeElement)
action(defaultValue, defaultValueSetter)
End Sub)
End Function
Friend Sub TestGetParameterPassingMode(code As XElement, expected As PARAMETER_PASSING_MODE)
TestElement(code,
Sub(codeElement)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
Dim actual = parameterKind.GetParameterPassingMode()
Assert.Equal(expected, actual)
End Sub)
End Sub
Friend Async Function TestSetParameterPassingMode(code As XElement, expectedCode As XElement, passingMode As PARAMETER_PASSING_MODE) As Task
Await TestSetParameterPassingMode(code, expectedCode, passingMode, NoThrow(Of PARAMETER_PASSING_MODE)())
End Function
Friend Async Function TestSetParameterPassingMode(code As XElement, expectedCode As XElement, passingMode As PARAMETER_PASSING_MODE, action As SetterAction(Of PARAMETER_PASSING_MODE)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim setter = Sub(mode As PARAMETER_PASSING_MODE)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
parameterKind.SetParameterPassingMode(mode)
End Sub
action(passingMode, setter)
End Sub)
End Function
Friend Sub TestGetParameterArrayCount(code As XElement, expected As Integer)
TestElement(code,
Sub(codeElement)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
Dim actual = parameterKind.GetParameterArrayCount()
Assert.Equal(expected, actual)
End Sub)
End Sub
Friend Sub TestGetParameterArrayDimensions(code As XElement, index As Integer, expected As Integer)
TestElement(code,
Sub(codeElement)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
Dim actual = parameterKind.GetParameterArrayDimensions(index)
Assert.Equal(expected, actual)
End Sub)
End Sub
Friend Async Function TestSetParameterArrayDimensions(code As XElement, expectedCode As XElement, dimensions As Integer) As Task
Await TestSetParameterArrayDimensions(code, expectedCode, dimensions, NoThrow(Of Integer)())
End Function
Friend Async Function TestSetParameterArrayDimensions(code As XElement, expectedCode As XElement, dimensions As Integer, action As SetterAction(Of Integer)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim setter = Sub(d As Integer)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
parameterKind.SetParameterArrayDimensions(d)
End Sub
action(dimensions, setter)
End Sub)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Public MustInherit Class AbstractCodeParameterTests
Inherits AbstractCodeElementTests(Of EnvDTE80.CodeParameter2)
Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeParameter2) As String
Throw New NotImplementedException()
End Function
Protected Function GetDefaultValueSetter(codeElement As EnvDTE80.CodeParameter2) As Action(Of String)
Return Sub(defaultValue) codeElement.DefaultValue = defaultValue
End Function
Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeParameter2) As String
Throw New NotImplementedException()
End Function
Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeParameter2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetEndPoint(part)
End Function
Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeParameter2) As String
Return codeElement.FullName
End Function
Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeParameter2) As EnvDTE.vsCMElement
Return codeElement.Kind
End Function
Protected Overrides Function GetName(codeElement As EnvDTE80.CodeParameter2) As String
Return codeElement.Name
End Function
Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeParameter2) As Action(Of String)
Throw New NotImplementedException()
End Function
Protected Function GetParameterKindSetter(codeElement As EnvDTE80.CodeParameter2) As Action(Of EnvDTE80.vsCMParameterKind)
Return Sub(kind) codeElement.ParameterKind = kind
End Function
Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeParameter2) As Object
Return codeElement.Parent
End Function
Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeParameter2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint)
Return Function(part) codeElement.GetStartPoint(part)
End Function
Protected Overrides Function GetTypeProp(codeElement As EnvDTE80.CodeParameter2) As EnvDTE.CodeTypeRef
Return codeElement.Type
End Function
Protected Overrides Function GetTypePropSetter(codeElement As EnvDTE80.CodeParameter2) As Action(Of EnvDTE.CodeTypeRef)
Return Sub(value) codeElement.Type = value
End Function
Protected Overrides Function AddAttribute(codeElement As EnvDTE80.CodeParameter2, data As AttributeData) As EnvDTE.CodeAttribute
Return codeElement.AddAttribute(data.Name, data.Value, data.Position)
End Function
Protected Sub TestParameterKind(code As XElement, kind As EnvDTE80.vsCMParameterKind)
TestElement(code,
Sub(codeElement)
Assert.Equal(kind, codeElement.ParameterKind)
End Sub)
End Sub
Protected Sub TestDefaultValue(code As XElement, expectedValue As String)
TestElement(code,
Sub(codeElement)
Assert.Equal(expectedValue, codeElement.DefaultValue)
End Sub)
End Sub
Protected Async Function TestSetParameterKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMParameterKind) As Task
Await TestSetParameterKind(code, expectedCode, kind, NoThrow(Of EnvDTE80.vsCMParameterKind)())
End Function
Protected Async Function TestSetParameterKind(code As XElement, expectedCode As XElement, kind As EnvDTE80.vsCMParameterKind, action As SetterAction(Of EnvDTE80.vsCMParameterKind)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim parameterKindSetter = GetParameterKindSetter(codeElement)
action(kind, parameterKindSetter)
End Sub)
End Function
Protected Async Function TestSetDefaultValue(code As XElement, expected As XElement, defaultValue As String) As Task
Await TestSetDefaultValue(code, expected, defaultValue, NoThrow(Of String)())
End Function
Protected Async Function TestSetDefaultValue(code As XElement, expectedCode As XElement, defaultValue As String, action As SetterAction(Of String)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim defaultValueSetter = GetDefaultValueSetter(codeElement)
action(defaultValue, defaultValueSetter)
End Sub)
End Function
Friend Sub TestGetParameterPassingMode(code As XElement, expected As PARAMETER_PASSING_MODE)
TestElement(code,
Sub(codeElement)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
Dim actual = parameterKind.GetParameterPassingMode()
Assert.Equal(expected, actual)
End Sub)
End Sub
Friend Async Function TestSetParameterPassingMode(code As XElement, expectedCode As XElement, passingMode As PARAMETER_PASSING_MODE) As Task
Await TestSetParameterPassingMode(code, expectedCode, passingMode, NoThrow(Of PARAMETER_PASSING_MODE)())
End Function
Friend Async Function TestSetParameterPassingMode(code As XElement, expectedCode As XElement, passingMode As PARAMETER_PASSING_MODE, action As SetterAction(Of PARAMETER_PASSING_MODE)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim setter = Sub(mode As PARAMETER_PASSING_MODE)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
parameterKind.SetParameterPassingMode(mode)
End Sub
action(passingMode, setter)
End Sub)
End Function
Friend Sub TestGetParameterArrayCount(code As XElement, expected As Integer)
TestElement(code,
Sub(codeElement)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
Dim actual = parameterKind.GetParameterArrayCount()
Assert.Equal(expected, actual)
End Sub)
End Sub
Friend Sub TestGetParameterArrayDimensions(code As XElement, index As Integer, expected As Integer)
TestElement(code,
Sub(codeElement)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
Dim actual = parameterKind.GetParameterArrayDimensions(index)
Assert.Equal(expected, actual)
End Sub)
End Sub
Friend Async Function TestSetParameterArrayDimensions(code As XElement, expectedCode As XElement, dimensions As Integer) As Task
Await TestSetParameterArrayDimensions(code, expectedCode, dimensions, NoThrow(Of Integer)())
End Function
Friend Async Function TestSetParameterArrayDimensions(code As XElement, expectedCode As XElement, dimensions As Integer, action As SetterAction(Of Integer)) As Task
Await TestElementUpdate(code, expectedCode,
Sub(codeElement)
Dim setter = Sub(d As Integer)
Dim parameterKind = TryCast(codeElement, IParameterKind)
Assert.NotNull(parameterKind)
parameterKind.SetParameterArrayDimensions(d)
End Sub
action(dimensions, setter)
End Sub)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Analyzers/VisualBasic/CodeFixes/SimplifyLinqExpression/VisualBasicSimplifyLinqExpressionCodeFixProvider.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.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SimplifyLinqExpression
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyLinqExpression
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.SimplifyLinqExpression), [Shared]>
Friend Class VisualBasicSimplifyLinqExpressionCodeFixProvider
Inherits AbstractSimplifyLinqExpressionCodeFixProvider(Of
InvocationExpressionSyntax, SimpleNameSyntax, ExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance
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.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SimplifyLinqExpression
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyLinqExpression
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.SimplifyLinqExpression), [Shared]>
Friend Class VisualBasicSimplifyLinqExpressionCodeFixProvider
Inherits AbstractSimplifyLinqExpressionCodeFixProvider(Of
InvocationExpressionSyntax, SimpleNameSyntax, ExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./docs/compilers/Compiler Toolset NuPkgs.md | Compiler Toolset NuPkgs
===
## Summary
The compiler produces the [Microsoft.Net.Compilers.Toolset NuPkg](https://www.nuget.org/packages/Microsoft.Net.Compilers.Toolset)
from all of Roslyn's main branches. When this NuPkg is installed it will
override the compiler that comes with MSBuild with the version from the branch
it was built in.
This package is meant to support the following scenarios:
1. Allows compiler team to provide rapid hot fixes to customers who hit a blocking
issue. This package can be installed until the fix is available in .NET SDK or
Visual Studio servicing.
1. Serves as a transport mechanism for the Roslyn binaries in the greater .NET
SDK build process.
1. Allows customers to conduct experiments on various Roslyn builds, many of
which aren't in an official shipping product yet.
This package is **not** meant to support using newer compiler versions in an
older version of MSBuild. For example using Microsoft.Net.Compilers.Toolset
3.5 (C# 8) inside MSBuild 15 is explicitly not a supported scenario.
Customers who want to use the compiler as a part of their supported build
infrastructure should use the [Visual Studio Build Tools SKU](https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-build-tools?view=vs-2022])
) or [.NET SDK](https://dotnet.microsoft.com/download/visual-studio-sdks)
## NuPkg Installation
To install the NuPgk run the following:
```cmd
> nuget install Microsoft.Net.Compilers.Toolset # Install C# and VB compilers
```
Daily NuGet builds of the project are also available in our [Azure DevOps feed](https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet-tools):
> https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json
## Microsoft.Net.Compilers
The [Microsoft.Net.Compilers](https://www.nuget.org/packages/Microsoft.Net.Compilers)
NuPkg is deprecated. It is a .NET Desktop specific version of
Microsoft.Net.Compilers.Toolset and will not be produced anymore after the
3.6.0 release. The Microsoft.Net.Compilers.Toolset package is a drop in
replacement for it for all supported scenarios.
| Compiler Toolset NuPkgs
===
## Summary
The compiler produces the [Microsoft.Net.Compilers.Toolset NuPkg](https://www.nuget.org/packages/Microsoft.Net.Compilers.Toolset)
from all of Roslyn's main branches. When this NuPkg is installed it will
override the compiler that comes with MSBuild with the version from the branch
it was built in.
This package is meant to support the following scenarios:
1. Allows compiler team to provide rapid hot fixes to customers who hit a blocking
issue. This package can be installed until the fix is available in .NET SDK or
Visual Studio servicing.
1. Serves as a transport mechanism for the Roslyn binaries in the greater .NET
SDK build process.
1. Allows customers to conduct experiments on various Roslyn builds, many of
which aren't in an official shipping product yet.
This package is **not** meant to support using newer compiler versions in an
older version of MSBuild. For example using Microsoft.Net.Compilers.Toolset
3.5 (C# 8) inside MSBuild 15 is explicitly not a supported scenario.
Customers who want to use the compiler as a part of their supported build
infrastructure should use the [Visual Studio Build Tools SKU](https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-build-tools?view=vs-2022])
) or [.NET SDK](https://dotnet.microsoft.com/download/visual-studio-sdks)
## NuPkg Installation
To install the NuPgk run the following:
```cmd
> nuget install Microsoft.Net.Compilers.Toolset # Install C# and VB compilers
```
Daily NuGet builds of the project are also available in our [Azure DevOps feed](https://dev.azure.com/dnceng/public/_packaging?_a=feed&feed=dotnet-tools):
> https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json
## Microsoft.Net.Compilers
The [Microsoft.Net.Compilers](https://www.nuget.org/packages/Microsoft.Net.Compilers)
NuPkg is deprecated. It is a .NET Desktop specific version of
Microsoft.Net.Compilers.Toolset and will not be produced anymore after the
3.6.0 release. The Microsoft.Net.Compilers.Toolset package is a drop in
replacement for it for all supported scenarios.
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptInlineRenameLocationSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptInlineRenameLocationSet
{
/// <summary>
/// The set of locations that need to be updated with the replacement text that the user
/// has entered in the inline rename session. These are the locations are all relative
/// to the solution when the inline rename session began.
/// </summary>
IList<VSTypeScriptInlineRenameLocationWrapper> Locations { get; }
/// <summary>
/// Returns the set of replacements and their possible resolutions if the user enters the
/// provided replacement text and options. Replacements are keyed by their document id
/// and TextSpan in the original solution, and specify their new span and possible conflict
/// resolution.
/// </summary>
Task<IVSTypeScriptInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptInlineRenameLocationSet
{
/// <summary>
/// The set of locations that need to be updated with the replacement text that the user
/// has entered in the inline rename session. These are the locations are all relative
/// to the solution when the inline rename session began.
/// </summary>
IList<VSTypeScriptInlineRenameLocationWrapper> Locations { get; }
/// <summary>
/// Returns the set of replacements and their possible resolutions if the user enters the
/// provided replacement text and options. Replacements are keyed by their document id
/// and TextSpan in the original solution, and specify their new span and possible conflict
/// resolution.
/// </summary>
Task<IVSTypeScriptInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol_Bases.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Collections;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class SourceNamedTypeSymbol
{
private Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> _lazyDeclaredBases;
private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyInterfaces;
/// <summary>
/// Gets the BaseType of this type. If the base type could not be determined, then
/// an instance of ErrorType is returned. If this kind of type does not have a base type
/// (for example, interfaces), null is returned. Also the special class System.Object
/// always has a BaseType of null.
/// </summary>
internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
{
get
{
if (ReferenceEquals(_lazyBaseType, ErrorTypeSymbol.UnknownResultType))
{
// force resolution of bases in containing type
// to make base resolution errors more deterministic
if ((object)ContainingType != null)
{
var tmp = ContainingType.BaseTypeNoUseSiteDiagnostics;
}
var diagnostics = BindingDiagnosticBag.GetInstance();
var acyclicBase = this.MakeAcyclicBaseType(diagnostics);
if (ReferenceEquals(Interlocked.CompareExchange(ref _lazyBaseType, acyclicBase, ErrorTypeSymbol.UnknownResultType), ErrorTypeSymbol.UnknownResultType))
{
AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
return _lazyBaseType;
}
}
/// <summary>
/// Gets the set of interfaces that this type directly implements. This set does not include
/// interfaces that are base interfaces of directly implemented interfaces.
/// </summary>
internal sealed override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyInterfaces.IsDefault)
{
if (basesBeingResolved != null && basesBeingResolved.ContainsReference(this.OriginalDefinition))
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
var diagnostics = BindingDiagnosticBag.GetInstance();
var acyclicInterfaces = MakeAcyclicInterfaces(basesBeingResolved, diagnostics);
if (ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, acyclicInterfaces, default(ImmutableArray<NamedTypeSymbol>)).IsDefault)
{
AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
return _lazyInterfaces;
}
protected override void CheckBase(BindingDiagnosticBag diagnostics)
{
var localBase = this.BaseTypeNoUseSiteDiagnostics;
if ((object)localBase == null)
{
// nothing to verify
return;
}
Location baseLocation = null;
bool baseContainsErrorTypes = localBase.ContainsErrorType();
if (!baseContainsErrorTypes)
{
baseLocation = FindBaseRefSyntax(localBase);
Debug.Assert(!this.IsClassType() || localBase.IsObjectType() || baseLocation != null);
}
// you need to know all bases before you can ask this question... (asking this causes a cycle)
if (this.IsGenericType && !baseContainsErrorTypes && this.DeclaringCompilation.IsAttributeType(localBase))
{
MessageID.IDS_FeatureGenericAttributes.CheckFeatureAvailability(diagnostics, this.DeclaringCompilation, baseLocation);
}
// Check constraints on the first declaration with explicit bases.
var singleDeclaration = this.FirstDeclarationWithExplicitBases();
if (singleDeclaration != null)
{
var corLibrary = this.ContainingAssembly.CorLibrary;
var conversions = new TypeConversions(corLibrary);
var location = singleDeclaration.NameLocation;
localBase.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics);
}
// Records can only inherit from other records or object
if (this.IsClassType() && !localBase.IsObjectType() && !baseContainsErrorTypes)
{
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
if (declaration.Kind == DeclarationKind.Record)
{
if (SynthesizedRecordClone.FindValidCloneMethod(localBase, ref useSiteInfo) is null)
{
diagnostics.Add(ErrorCode.ERR_BadRecordBase, baseLocation);
}
}
else if (SynthesizedRecordClone.FindValidCloneMethod(localBase, ref useSiteInfo) is object)
{
diagnostics.Add(ErrorCode.ERR_BadInheritanceFromRecord, baseLocation);
}
diagnostics.Add(baseLocation, useSiteInfo);
}
}
protected override void CheckInterfaces(BindingDiagnosticBag diagnostics)
{
// Check declared interfaces and all base interfaces. This is necessary
// since references to all interfaces will be emitted to metadata
// and it's possible to define derived interfaces with weaker
// constraints than the base interfaces, at least in metadata.
var interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;
if (interfaces.IsEmpty)
{
// nothing to verify
return;
}
// Check constraints on the first declaration with explicit bases.
var singleDeclaration = this.FirstDeclarationWithExplicitBases();
if (singleDeclaration != null)
{
var corLibrary = this.ContainingAssembly.CorLibrary;
var conversions = new TypeConversions(corLibrary);
var location = singleDeclaration.NameLocation;
foreach (var pair in interfaces)
{
MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>.ValueSet set = pair.Value;
foreach (var @interface in set)
{
@interface.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics);
}
if (set.Count > 1)
{
NamedTypeSymbol other = pair.Key;
foreach (var @interface in set)
{
if ((object)other == @interface)
{
continue;
}
// InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics populates the set with interfaces that match by CLR signature.
Debug.Assert(!other.Equals(@interface, TypeCompareKind.ConsiderEverything));
Debug.Assert(other.Equals(@interface, TypeCompareKind.CLRSignatureCompareOptions));
if (other.Equals(@interface, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
if (!other.Equals(@interface, TypeCompareKind.ObliviousNullableModifierMatchesAny))
{
diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, location, @interface, this);
}
}
else if (other.Equals(@interface, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, location, @interface, other, this);
}
else
{
diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList, location, @interface, other, this);
}
}
}
}
}
}
// finds syntax location where given type was inherited
// should be used for error reporting on unexpected inherited types.
private SourceLocation FindBaseRefSyntax(NamedTypeSymbol baseSym)
{
foreach (var decl in this.declaration.Declarations)
{
BaseListSyntax bases = GetBaseListOpt(decl);
if (bases != null)
{
var baseBinder = this.DeclaringCompilation.GetBinder(bases);
// Wrap base binder in a location-specific binder that will avoid generic constraint checks.
baseBinder = baseBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
foreach (var baseTypeSyntax in bases.Types)
{
var b = baseTypeSyntax.Type;
var curBaseSym = baseBinder.BindType(b, BindingDiagnosticBag.Discarded).Type;
if (baseSym.Equals(curBaseSym))
{
return new SourceLocation(b);
}
}
}
}
return null;
}
// Returns the first declaration in the merged declarations list that includes
// base types or interfaces. Returns null if there are no such declarations.
private SingleTypeDeclaration FirstDeclarationWithExplicitBases()
{
foreach (var singleDeclaration in this.declaration.Declarations)
{
var bases = GetBaseListOpt(singleDeclaration);
if (bases != null)
{
return singleDeclaration;
}
}
return null;
}
internal Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> GetDeclaredBases(ConsList<TypeSymbol> basesBeingResolved)
{
if (ReferenceEquals(_lazyDeclaredBases, null))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
if (Interlocked.CompareExchange(ref _lazyDeclaredBases, MakeDeclaredBases(basesBeingResolved, diagnostics), null) == null)
{
AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
return _lazyDeclaredBases;
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
return GetDeclaredBases(basesBeingResolved).Item1;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
return GetDeclaredBases(basesBeingResolved).Item2;
}
private Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> MakeDeclaredBases(ConsList<TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics)
{
if (this.TypeKind == TypeKind.Enum)
{
// Handled by GetEnumUnderlyingType().
return new Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>>(null, ImmutableArray<NamedTypeSymbol>.Empty);
}
var reportedPartialConflict = false;
Debug.Assert(basesBeingResolved == null || !basesBeingResolved.ContainsReference(this.OriginalDefinition));
var newBasesBeingResolved = basesBeingResolved.Prepend(this.OriginalDefinition);
var baseInterfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance();
NamedTypeSymbol baseType = null;
SourceLocation baseTypeLocation = null;
var interfaceLocations = SpecializedSymbolCollections.GetPooledSymbolDictionaryInstance<NamedTypeSymbol, SourceLocation>();
foreach (var decl in this.declaration.Declarations)
{
Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> one = MakeOneDeclaredBases(newBasesBeingResolved, decl, diagnostics);
if ((object)one == null) continue;
var partBase = one.Item1;
var partInterfaces = one.Item2;
if (!reportedPartialConflict)
{
if ((object)baseType == null)
{
baseType = partBase;
baseTypeLocation = decl.NameLocation;
}
else if (baseType.TypeKind == TypeKind.Error && (object)partBase != null)
{
// if the old base was an error symbol, copy it to the interfaces list so it doesn't get lost
partInterfaces = partInterfaces.Add(baseType);
baseType = partBase;
baseTypeLocation = decl.NameLocation;
}
else if ((object)partBase != null && !TypeSymbol.Equals(partBase, baseType, TypeCompareKind.ConsiderEverything) && partBase.TypeKind != TypeKind.Error)
{
// the parts do not agree
if (partBase.Equals(baseType, TypeCompareKind.ObliviousNullableModifierMatchesAny))
{
if (containsOnlyOblivious(baseType))
{
baseType = partBase;
baseTypeLocation = decl.NameLocation;
continue;
}
else if (containsOnlyOblivious(partBase))
{
continue;
}
}
var info = diagnostics.Add(ErrorCode.ERR_PartialMultipleBases, Locations[0], this);
baseType = new ExtendedErrorTypeSymbol(baseType, LookupResultKind.Ambiguous, info);
baseTypeLocation = decl.NameLocation;
reportedPartialConflict = true;
static bool containsOnlyOblivious(TypeSymbol type)
{
return TypeWithAnnotations.Create(type).VisitType(
type: null,
static (type, arg, flag) => !type.Type.IsValueType && !type.NullableAnnotation.IsOblivious(),
typePredicate: null,
arg: (object)null) is null;
}
}
}
foreach (var t in partInterfaces)
{
if (!interfaceLocations.ContainsKey(t))
{
baseInterfaces.Add(t);
interfaceLocations.Add(t, decl.NameLocation);
}
}
}
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
if (declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct)
{
var type = DeclaringCompilation.GetWellKnownType(WellKnownType.System_IEquatable_T).Construct(this);
if (baseInterfaces.IndexOf(type, SymbolEqualityComparer.AllIgnoreOptions) < 0)
{
baseInterfaces.Add(type);
type.AddUseSiteInfo(ref useSiteInfo);
}
}
if ((object)baseType != null)
{
Debug.Assert(baseTypeLocation != null);
if (baseType.IsStatic)
{
// '{1}': cannot derive from static class '{0}'
diagnostics.Add(ErrorCode.ERR_StaticBaseClass, baseTypeLocation, baseType, this);
}
if (!this.IsNoMoreVisibleThan(baseType, ref useSiteInfo))
{
// Inconsistent accessibility: base class '{1}' is less accessible than class '{0}'
diagnostics.Add(ErrorCode.ERR_BadVisBaseClass, baseTypeLocation, this, baseType);
}
}
var baseInterfacesRO = baseInterfaces.ToImmutableAndFree();
if (DeclaredAccessibility != Accessibility.Private && IsInterface)
{
foreach (var i in baseInterfacesRO)
{
if (!i.IsAtLeastAsVisibleAs(this, ref useSiteInfo))
{
// Inconsistent accessibility: base interface '{1}' is less accessible than interface '{0}'
diagnostics.Add(ErrorCode.ERR_BadVisBaseInterface, interfaceLocations[i], this, i);
}
}
}
interfaceLocations.Free();
diagnostics.Add(Locations[0], useSiteInfo);
return new Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>>(baseType, baseInterfacesRO);
}
private static BaseListSyntax GetBaseListOpt(SingleTypeDeclaration decl)
{
if (decl.HasBaseDeclarations)
{
var typeDeclaration = (BaseTypeDeclarationSyntax)decl.SyntaxReference.GetSyntax();
return typeDeclaration.BaseList;
}
return null;
}
// process the base list for one part of a partial class, or for the only part of any other type declaration.
private Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> MakeOneDeclaredBases(ConsList<TypeSymbol> newBasesBeingResolved, SingleTypeDeclaration decl, BindingDiagnosticBag diagnostics)
{
BaseListSyntax bases = GetBaseListOpt(decl);
if (bases == null)
{
return null;
}
NamedTypeSymbol localBase = null;
var localInterfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance();
var baseBinder = this.DeclaringCompilation.GetBinder(bases);
// Wrap base binder in a location-specific binder that will avoid generic constraint checks
// (to avoid cycles if the constraint types are not bound yet). Instead, constraint checks
// are handled by the caller.
baseBinder = baseBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
int i = -1;
foreach (var baseTypeSyntax in bases.Types)
{
i++;
var typeSyntax = baseTypeSyntax.Type;
if (typeSyntax.Kind() != SyntaxKind.PredefinedType && !SyntaxFacts.IsName(typeSyntax.Kind()))
{
diagnostics.Add(ErrorCode.ERR_BadBaseType, typeSyntax.GetLocation());
}
var location = new SourceLocation(typeSyntax);
TypeSymbol baseType;
if (i == 0 && TypeKind == TypeKind.Class) // allow class in the first position
{
baseType = baseBinder.BindType(typeSyntax, diagnostics, newBasesBeingResolved).Type;
SpecialType baseSpecialType = baseType.SpecialType;
if (IsRestrictedBaseType(baseSpecialType))
{
// check for one of the specific exceptions required for compiling mscorlib
if (this.SpecialType == SpecialType.System_Enum && baseSpecialType == SpecialType.System_ValueType ||
this.SpecialType == SpecialType.System_MulticastDelegate && baseSpecialType == SpecialType.System_Delegate)
{
// allowed
}
else if (baseSpecialType == SpecialType.System_Array && this.ContainingAssembly.CorLibrary == this.ContainingAssembly)
{
// Specific exception for System.ArrayContracts, which is only built when CONTRACTS_FULL is defined.
// (See InheritanceResolver::CheckForBaseClassErrors).
}
else
{
// '{0}' cannot derive from special class '{1}'
diagnostics.Add(ErrorCode.ERR_DeriveFromEnumOrValueType, location, this, baseType);
continue;
}
}
if (baseType.IsSealed && !this.IsStatic) // Give precedence to ERR_StaticDerivedFromNonObject
{
diagnostics.Add(ErrorCode.ERR_CantDeriveFromSealedType, location, this, baseType);
continue;
}
bool baseTypeIsErrorWithoutInterfaceGuess = false;
// If baseType is an error symbol and our best guess is that the desired symbol
// is an interface, then put baseType in the interfaces list, rather than the
// base type slot, to avoid the frustrating scenario where an error message
// indicates that the symbol being returned as the base type was elsewhere
// interpreted as an interface.
if (baseType.TypeKind == TypeKind.Error)
{
baseTypeIsErrorWithoutInterfaceGuess = true;
TypeKind guessTypeKind = baseType.GetNonErrorTypeKindGuess();
if (guessTypeKind == TypeKind.Interface)
{
//base type is an error *with* a guessed interface
baseTypeIsErrorWithoutInterfaceGuess = false;
}
}
if ((baseType.TypeKind == TypeKind.Class ||
baseType.TypeKind == TypeKind.Delegate ||
baseType.TypeKind == TypeKind.Struct ||
baseTypeIsErrorWithoutInterfaceGuess) &&
((object)localBase == null))
{
localBase = (NamedTypeSymbol)baseType;
Debug.Assert((object)localBase != null);
if (this.IsStatic && localBase.SpecialType != SpecialType.System_Object)
{
// Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object.
var info = diagnostics.Add(ErrorCode.ERR_StaticDerivedFromNonObject, location, this, localBase);
localBase = new ExtendedErrorTypeSymbol(localBase, LookupResultKind.NotReferencable, info);
}
checkPrimaryConstructorBaseType(baseTypeSyntax, localBase);
continue;
}
}
else
{
baseType = baseBinder.BindType(typeSyntax, diagnostics, newBasesBeingResolved).Type;
}
if (i == 0)
{
checkPrimaryConstructorBaseType(baseTypeSyntax, baseType);
}
switch (baseType.TypeKind)
{
case TypeKind.Interface:
foreach (var t in localInterfaces)
{
if (t.Equals(baseType, TypeCompareKind.ConsiderEverything))
{
diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceInBaseList, location, baseType);
}
else if (t.Equals(baseType, TypeCompareKind.ObliviousNullableModifierMatchesAny))
{
// duplicates with ?/! differences are reported later, we report local differences between oblivious and ?/! here
diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, location, baseType, this);
}
}
if (this.IsStatic)
{
// '{0}': static classes cannot implement interfaces
diagnostics.Add(ErrorCode.ERR_StaticClassInterfaceImpl, location, this, baseType);
}
if (this.IsRefLikeType)
{
// '{0}': ref structs cannot implement interfaces
diagnostics.Add(ErrorCode.ERR_RefStructInterfaceImpl, location, this, baseType);
}
if (baseType.ContainsDynamic())
{
diagnostics.Add(ErrorCode.ERR_DeriveFromConstructedDynamic, location, this, baseType);
}
localInterfaces.Add((NamedTypeSymbol)baseType);
continue;
case TypeKind.Class:
if (TypeKind == TypeKind.Class)
{
if ((object)localBase == null)
{
localBase = (NamedTypeSymbol)baseType;
diagnostics.Add(ErrorCode.ERR_BaseClassMustBeFirst, location, baseType);
continue;
}
else
{
diagnostics.Add(ErrorCode.ERR_NoMultipleInheritance, location, this, localBase, baseType);
continue;
}
}
goto default;
case TypeKind.TypeParameter:
diagnostics.Add(ErrorCode.ERR_DerivingFromATyVar, location, baseType);
continue;
case TypeKind.Error:
// put the error type in the interface list so we don't lose track of it
localInterfaces.Add((NamedTypeSymbol)baseType);
continue;
case TypeKind.Dynamic:
diagnostics.Add(ErrorCode.ERR_DeriveFromDynamic, location, this);
continue;
case TypeKind.Submission:
throw ExceptionUtilities.UnexpectedValue(baseType.TypeKind);
default:
diagnostics.Add(ErrorCode.ERR_NonInterfaceInInterfaceList, location, baseType);
continue;
}
}
if (this.SpecialType == SpecialType.System_Object && ((object)localBase != null || localInterfaces.Count != 0))
{
var name = GetName(bases.Parent);
diagnostics.Add(ErrorCode.ERR_ObjectCantHaveBases, new SourceLocation(name));
}
return new Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>>(localBase, localInterfaces.ToImmutableAndFree());
void checkPrimaryConstructorBaseType(BaseTypeSyntax baseTypeSyntax, TypeSymbol baseType)
{
if (baseTypeSyntax is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType &&
(!IsRecord || TypeKind != TypeKind.Class || baseType.TypeKind == TypeKind.Interface || ((RecordDeclarationSyntax)decl.SyntaxReference.GetSyntax()).ParameterList is null))
{
diagnostics.Add(ErrorCode.ERR_UnexpectedArgumentList, primaryConstructorBaseType.ArgumentList.Location);
}
}
}
/// <summary>
/// Returns true if the type cannot be used as an explicit base class.
/// </summary>
private static bool IsRestrictedBaseType(SpecialType specialType)
{
switch (specialType)
{
case SpecialType.System_Array:
case SpecialType.System_Enum:
case SpecialType.System_Delegate:
case SpecialType.System_MulticastDelegate:
case SpecialType.System_ValueType:
return true;
}
return false;
}
private ImmutableArray<NamedTypeSymbol> MakeAcyclicInterfaces(ConsList<TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics)
{
var typeKind = this.TypeKind;
if (typeKind == TypeKind.Enum)
{
Debug.Assert(GetDeclaredInterfaces(basesBeingResolved: null).IsEmpty, "Computation skipped for enums");
return ImmutableArray<NamedTypeSymbol>.Empty;
}
var declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved: basesBeingResolved);
bool isInterface = (typeKind == TypeKind.Interface);
ArrayBuilder<NamedTypeSymbol> result = isInterface ? ArrayBuilder<NamedTypeSymbol>.GetInstance() : null;
foreach (var t in declaredInterfaces)
{
if (isInterface)
{
if (BaseTypeAnalysis.TypeDependsOn(depends: t, on: this))
{
result.Add(new ExtendedErrorTypeSymbol(t, LookupResultKind.NotReferencable,
diagnostics.Add(ErrorCode.ERR_CycleInInterfaceInheritance, Locations[0], this, t)));
continue;
}
else
{
result.Add(t);
}
}
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
if (t.DeclaringCompilation != this.DeclaringCompilation)
{
t.AddUseSiteInfo(ref useSiteInfo);
foreach (var @interface in t.AllInterfacesNoUseSiteDiagnostics)
{
if (@interface.DeclaringCompilation != this.DeclaringCompilation)
{
@interface.AddUseSiteInfo(ref useSiteInfo);
}
}
}
diagnostics.Add(Locations[0], useSiteInfo);
}
return isInterface ? result.ToImmutableAndFree() : declaredInterfaces;
}
private NamedTypeSymbol MakeAcyclicBaseType(BindingDiagnosticBag diagnostics)
{
var typeKind = this.TypeKind;
var compilation = this.DeclaringCompilation;
NamedTypeSymbol declaredBase;
if (typeKind == TypeKind.Enum)
{
Debug.Assert((object)GetDeclaredBaseType(basesBeingResolved: null) == null, "Computation skipped for enums");
declaredBase = compilation.GetSpecialType(SpecialType.System_Enum);
}
else
{
declaredBase = GetDeclaredBaseType(basesBeingResolved: null);
}
if ((object)declaredBase == null)
{
switch (typeKind)
{
case TypeKind.Class:
if (this.SpecialType == SpecialType.System_Object)
{
return null;
}
declaredBase = compilation.GetSpecialType(SpecialType.System_Object);
break;
case TypeKind.Struct:
declaredBase = compilation.GetSpecialType(SpecialType.System_ValueType);
break;
case TypeKind.Interface:
return null;
case TypeKind.Delegate:
declaredBase = compilation.GetSpecialType(SpecialType.System_MulticastDelegate);
break;
default:
throw ExceptionUtilities.UnexpectedValue(typeKind);
}
}
if (BaseTypeAnalysis.TypeDependsOn(declaredBase, this))
{
return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable,
diagnostics.Add(ErrorCode.ERR_CircularBase, Locations[0], declaredBase, this));
}
this.SetKnownToHaveNoDeclaredBaseCycles();
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
NamedTypeSymbol current = declaredBase;
do
{
if (current.DeclaringCompilation == this.DeclaringCompilation)
{
break;
}
current.AddUseSiteInfo(ref useSiteInfo);
current = current.BaseTypeNoUseSiteDiagnostics;
}
while ((object)current != null);
diagnostics.Add(useSiteInfo.Diagnostics.IsNullOrEmpty() ? Location.None : (FindBaseRefSyntax(declaredBase) ?? Locations[0]), useSiteInfo);
return declaredBase;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Collections;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class SourceNamedTypeSymbol
{
private Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> _lazyDeclaredBases;
private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyInterfaces;
/// <summary>
/// Gets the BaseType of this type. If the base type could not be determined, then
/// an instance of ErrorType is returned. If this kind of type does not have a base type
/// (for example, interfaces), null is returned. Also the special class System.Object
/// always has a BaseType of null.
/// </summary>
internal sealed override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
{
get
{
if (ReferenceEquals(_lazyBaseType, ErrorTypeSymbol.UnknownResultType))
{
// force resolution of bases in containing type
// to make base resolution errors more deterministic
if ((object)ContainingType != null)
{
var tmp = ContainingType.BaseTypeNoUseSiteDiagnostics;
}
var diagnostics = BindingDiagnosticBag.GetInstance();
var acyclicBase = this.MakeAcyclicBaseType(diagnostics);
if (ReferenceEquals(Interlocked.CompareExchange(ref _lazyBaseType, acyclicBase, ErrorTypeSymbol.UnknownResultType), ErrorTypeSymbol.UnknownResultType))
{
AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
return _lazyBaseType;
}
}
/// <summary>
/// Gets the set of interfaces that this type directly implements. This set does not include
/// interfaces that are base interfaces of directly implemented interfaces.
/// </summary>
internal sealed override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyInterfaces.IsDefault)
{
if (basesBeingResolved != null && basesBeingResolved.ContainsReference(this.OriginalDefinition))
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
var diagnostics = BindingDiagnosticBag.GetInstance();
var acyclicInterfaces = MakeAcyclicInterfaces(basesBeingResolved, diagnostics);
if (ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, acyclicInterfaces, default(ImmutableArray<NamedTypeSymbol>)).IsDefault)
{
AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
return _lazyInterfaces;
}
protected override void CheckBase(BindingDiagnosticBag diagnostics)
{
var localBase = this.BaseTypeNoUseSiteDiagnostics;
if ((object)localBase == null)
{
// nothing to verify
return;
}
Location baseLocation = null;
bool baseContainsErrorTypes = localBase.ContainsErrorType();
if (!baseContainsErrorTypes)
{
baseLocation = FindBaseRefSyntax(localBase);
Debug.Assert(!this.IsClassType() || localBase.IsObjectType() || baseLocation != null);
}
// you need to know all bases before you can ask this question... (asking this causes a cycle)
if (this.IsGenericType && !baseContainsErrorTypes && this.DeclaringCompilation.IsAttributeType(localBase))
{
MessageID.IDS_FeatureGenericAttributes.CheckFeatureAvailability(diagnostics, this.DeclaringCompilation, baseLocation);
}
// Check constraints on the first declaration with explicit bases.
var singleDeclaration = this.FirstDeclarationWithExplicitBases();
if (singleDeclaration != null)
{
var corLibrary = this.ContainingAssembly.CorLibrary;
var conversions = new TypeConversions(corLibrary);
var location = singleDeclaration.NameLocation;
localBase.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics);
}
// Records can only inherit from other records or object
if (this.IsClassType() && !localBase.IsObjectType() && !baseContainsErrorTypes)
{
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
if (declaration.Kind == DeclarationKind.Record)
{
if (SynthesizedRecordClone.FindValidCloneMethod(localBase, ref useSiteInfo) is null)
{
diagnostics.Add(ErrorCode.ERR_BadRecordBase, baseLocation);
}
}
else if (SynthesizedRecordClone.FindValidCloneMethod(localBase, ref useSiteInfo) is object)
{
diagnostics.Add(ErrorCode.ERR_BadInheritanceFromRecord, baseLocation);
}
diagnostics.Add(baseLocation, useSiteInfo);
}
}
protected override void CheckInterfaces(BindingDiagnosticBag diagnostics)
{
// Check declared interfaces and all base interfaces. This is necessary
// since references to all interfaces will be emitted to metadata
// and it's possible to define derived interfaces with weaker
// constraints than the base interfaces, at least in metadata.
var interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;
if (interfaces.IsEmpty)
{
// nothing to verify
return;
}
// Check constraints on the first declaration with explicit bases.
var singleDeclaration = this.FirstDeclarationWithExplicitBases();
if (singleDeclaration != null)
{
var corLibrary = this.ContainingAssembly.CorLibrary;
var conversions = new TypeConversions(corLibrary);
var location = singleDeclaration.NameLocation;
foreach (var pair in interfaces)
{
MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>.ValueSet set = pair.Value;
foreach (var @interface in set)
{
@interface.CheckAllConstraints(DeclaringCompilation, conversions, location, diagnostics);
}
if (set.Count > 1)
{
NamedTypeSymbol other = pair.Key;
foreach (var @interface in set)
{
if ((object)other == @interface)
{
continue;
}
// InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics populates the set with interfaces that match by CLR signature.
Debug.Assert(!other.Equals(@interface, TypeCompareKind.ConsiderEverything));
Debug.Assert(other.Equals(@interface, TypeCompareKind.CLRSignatureCompareOptions));
if (other.Equals(@interface, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
if (!other.Equals(@interface, TypeCompareKind.ObliviousNullableModifierMatchesAny))
{
diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, location, @interface, this);
}
}
else if (other.Equals(@interface, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))
{
diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, location, @interface, other, this);
}
else
{
diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList, location, @interface, other, this);
}
}
}
}
}
}
// finds syntax location where given type was inherited
// should be used for error reporting on unexpected inherited types.
private SourceLocation FindBaseRefSyntax(NamedTypeSymbol baseSym)
{
foreach (var decl in this.declaration.Declarations)
{
BaseListSyntax bases = GetBaseListOpt(decl);
if (bases != null)
{
var baseBinder = this.DeclaringCompilation.GetBinder(bases);
// Wrap base binder in a location-specific binder that will avoid generic constraint checks.
baseBinder = baseBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
foreach (var baseTypeSyntax in bases.Types)
{
var b = baseTypeSyntax.Type;
var curBaseSym = baseBinder.BindType(b, BindingDiagnosticBag.Discarded).Type;
if (baseSym.Equals(curBaseSym))
{
return new SourceLocation(b);
}
}
}
}
return null;
}
// Returns the first declaration in the merged declarations list that includes
// base types or interfaces. Returns null if there are no such declarations.
private SingleTypeDeclaration FirstDeclarationWithExplicitBases()
{
foreach (var singleDeclaration in this.declaration.Declarations)
{
var bases = GetBaseListOpt(singleDeclaration);
if (bases != null)
{
return singleDeclaration;
}
}
return null;
}
internal Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> GetDeclaredBases(ConsList<TypeSymbol> basesBeingResolved)
{
if (ReferenceEquals(_lazyDeclaredBases, null))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
if (Interlocked.CompareExchange(ref _lazyDeclaredBases, MakeDeclaredBases(basesBeingResolved, diagnostics), null) == null)
{
AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
return _lazyDeclaredBases;
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
return GetDeclaredBases(basesBeingResolved).Item1;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
return GetDeclaredBases(basesBeingResolved).Item2;
}
private Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> MakeDeclaredBases(ConsList<TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics)
{
if (this.TypeKind == TypeKind.Enum)
{
// Handled by GetEnumUnderlyingType().
return new Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>>(null, ImmutableArray<NamedTypeSymbol>.Empty);
}
var reportedPartialConflict = false;
Debug.Assert(basesBeingResolved == null || !basesBeingResolved.ContainsReference(this.OriginalDefinition));
var newBasesBeingResolved = basesBeingResolved.Prepend(this.OriginalDefinition);
var baseInterfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance();
NamedTypeSymbol baseType = null;
SourceLocation baseTypeLocation = null;
var interfaceLocations = SpecializedSymbolCollections.GetPooledSymbolDictionaryInstance<NamedTypeSymbol, SourceLocation>();
foreach (var decl in this.declaration.Declarations)
{
Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> one = MakeOneDeclaredBases(newBasesBeingResolved, decl, diagnostics);
if ((object)one == null) continue;
var partBase = one.Item1;
var partInterfaces = one.Item2;
if (!reportedPartialConflict)
{
if ((object)baseType == null)
{
baseType = partBase;
baseTypeLocation = decl.NameLocation;
}
else if (baseType.TypeKind == TypeKind.Error && (object)partBase != null)
{
// if the old base was an error symbol, copy it to the interfaces list so it doesn't get lost
partInterfaces = partInterfaces.Add(baseType);
baseType = partBase;
baseTypeLocation = decl.NameLocation;
}
else if ((object)partBase != null && !TypeSymbol.Equals(partBase, baseType, TypeCompareKind.ConsiderEverything) && partBase.TypeKind != TypeKind.Error)
{
// the parts do not agree
if (partBase.Equals(baseType, TypeCompareKind.ObliviousNullableModifierMatchesAny))
{
if (containsOnlyOblivious(baseType))
{
baseType = partBase;
baseTypeLocation = decl.NameLocation;
continue;
}
else if (containsOnlyOblivious(partBase))
{
continue;
}
}
var info = diagnostics.Add(ErrorCode.ERR_PartialMultipleBases, Locations[0], this);
baseType = new ExtendedErrorTypeSymbol(baseType, LookupResultKind.Ambiguous, info);
baseTypeLocation = decl.NameLocation;
reportedPartialConflict = true;
static bool containsOnlyOblivious(TypeSymbol type)
{
return TypeWithAnnotations.Create(type).VisitType(
type: null,
static (type, arg, flag) => !type.Type.IsValueType && !type.NullableAnnotation.IsOblivious(),
typePredicate: null,
arg: (object)null) is null;
}
}
}
foreach (var t in partInterfaces)
{
if (!interfaceLocations.ContainsKey(t))
{
baseInterfaces.Add(t);
interfaceLocations.Add(t, decl.NameLocation);
}
}
}
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
if (declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct)
{
var type = DeclaringCompilation.GetWellKnownType(WellKnownType.System_IEquatable_T).Construct(this);
if (baseInterfaces.IndexOf(type, SymbolEqualityComparer.AllIgnoreOptions) < 0)
{
baseInterfaces.Add(type);
type.AddUseSiteInfo(ref useSiteInfo);
}
}
if ((object)baseType != null)
{
Debug.Assert(baseTypeLocation != null);
if (baseType.IsStatic)
{
// '{1}': cannot derive from static class '{0}'
diagnostics.Add(ErrorCode.ERR_StaticBaseClass, baseTypeLocation, baseType, this);
}
if (!this.IsNoMoreVisibleThan(baseType, ref useSiteInfo))
{
// Inconsistent accessibility: base class '{1}' is less accessible than class '{0}'
diagnostics.Add(ErrorCode.ERR_BadVisBaseClass, baseTypeLocation, this, baseType);
}
}
var baseInterfacesRO = baseInterfaces.ToImmutableAndFree();
if (DeclaredAccessibility != Accessibility.Private && IsInterface)
{
foreach (var i in baseInterfacesRO)
{
if (!i.IsAtLeastAsVisibleAs(this, ref useSiteInfo))
{
// Inconsistent accessibility: base interface '{1}' is less accessible than interface '{0}'
diagnostics.Add(ErrorCode.ERR_BadVisBaseInterface, interfaceLocations[i], this, i);
}
}
}
interfaceLocations.Free();
diagnostics.Add(Locations[0], useSiteInfo);
return new Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>>(baseType, baseInterfacesRO);
}
private static BaseListSyntax GetBaseListOpt(SingleTypeDeclaration decl)
{
if (decl.HasBaseDeclarations)
{
var typeDeclaration = (BaseTypeDeclarationSyntax)decl.SyntaxReference.GetSyntax();
return typeDeclaration.BaseList;
}
return null;
}
// process the base list for one part of a partial class, or for the only part of any other type declaration.
private Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>> MakeOneDeclaredBases(ConsList<TypeSymbol> newBasesBeingResolved, SingleTypeDeclaration decl, BindingDiagnosticBag diagnostics)
{
BaseListSyntax bases = GetBaseListOpt(decl);
if (bases == null)
{
return null;
}
NamedTypeSymbol localBase = null;
var localInterfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance();
var baseBinder = this.DeclaringCompilation.GetBinder(bases);
// Wrap base binder in a location-specific binder that will avoid generic constraint checks
// (to avoid cycles if the constraint types are not bound yet). Instead, constraint checks
// are handled by the caller.
baseBinder = baseBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
int i = -1;
foreach (var baseTypeSyntax in bases.Types)
{
i++;
var typeSyntax = baseTypeSyntax.Type;
if (typeSyntax.Kind() != SyntaxKind.PredefinedType && !SyntaxFacts.IsName(typeSyntax.Kind()))
{
diagnostics.Add(ErrorCode.ERR_BadBaseType, typeSyntax.GetLocation());
}
var location = new SourceLocation(typeSyntax);
TypeSymbol baseType;
if (i == 0 && TypeKind == TypeKind.Class) // allow class in the first position
{
baseType = baseBinder.BindType(typeSyntax, diagnostics, newBasesBeingResolved).Type;
SpecialType baseSpecialType = baseType.SpecialType;
if (IsRestrictedBaseType(baseSpecialType))
{
// check for one of the specific exceptions required for compiling mscorlib
if (this.SpecialType == SpecialType.System_Enum && baseSpecialType == SpecialType.System_ValueType ||
this.SpecialType == SpecialType.System_MulticastDelegate && baseSpecialType == SpecialType.System_Delegate)
{
// allowed
}
else if (baseSpecialType == SpecialType.System_Array && this.ContainingAssembly.CorLibrary == this.ContainingAssembly)
{
// Specific exception for System.ArrayContracts, which is only built when CONTRACTS_FULL is defined.
// (See InheritanceResolver::CheckForBaseClassErrors).
}
else
{
// '{0}' cannot derive from special class '{1}'
diagnostics.Add(ErrorCode.ERR_DeriveFromEnumOrValueType, location, this, baseType);
continue;
}
}
if (baseType.IsSealed && !this.IsStatic) // Give precedence to ERR_StaticDerivedFromNonObject
{
diagnostics.Add(ErrorCode.ERR_CantDeriveFromSealedType, location, this, baseType);
continue;
}
bool baseTypeIsErrorWithoutInterfaceGuess = false;
// If baseType is an error symbol and our best guess is that the desired symbol
// is an interface, then put baseType in the interfaces list, rather than the
// base type slot, to avoid the frustrating scenario where an error message
// indicates that the symbol being returned as the base type was elsewhere
// interpreted as an interface.
if (baseType.TypeKind == TypeKind.Error)
{
baseTypeIsErrorWithoutInterfaceGuess = true;
TypeKind guessTypeKind = baseType.GetNonErrorTypeKindGuess();
if (guessTypeKind == TypeKind.Interface)
{
//base type is an error *with* a guessed interface
baseTypeIsErrorWithoutInterfaceGuess = false;
}
}
if ((baseType.TypeKind == TypeKind.Class ||
baseType.TypeKind == TypeKind.Delegate ||
baseType.TypeKind == TypeKind.Struct ||
baseTypeIsErrorWithoutInterfaceGuess) &&
((object)localBase == null))
{
localBase = (NamedTypeSymbol)baseType;
Debug.Assert((object)localBase != null);
if (this.IsStatic && localBase.SpecialType != SpecialType.System_Object)
{
// Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object.
var info = diagnostics.Add(ErrorCode.ERR_StaticDerivedFromNonObject, location, this, localBase);
localBase = new ExtendedErrorTypeSymbol(localBase, LookupResultKind.NotReferencable, info);
}
checkPrimaryConstructorBaseType(baseTypeSyntax, localBase);
continue;
}
}
else
{
baseType = baseBinder.BindType(typeSyntax, diagnostics, newBasesBeingResolved).Type;
}
if (i == 0)
{
checkPrimaryConstructorBaseType(baseTypeSyntax, baseType);
}
switch (baseType.TypeKind)
{
case TypeKind.Interface:
foreach (var t in localInterfaces)
{
if (t.Equals(baseType, TypeCompareKind.ConsiderEverything))
{
diagnostics.Add(ErrorCode.ERR_DuplicateInterfaceInBaseList, location, baseType);
}
else if (t.Equals(baseType, TypeCompareKind.ObliviousNullableModifierMatchesAny))
{
// duplicates with ?/! differences are reported later, we report local differences between oblivious and ?/! here
diagnostics.Add(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, location, baseType, this);
}
}
if (this.IsStatic)
{
// '{0}': static classes cannot implement interfaces
diagnostics.Add(ErrorCode.ERR_StaticClassInterfaceImpl, location, this, baseType);
}
if (this.IsRefLikeType)
{
// '{0}': ref structs cannot implement interfaces
diagnostics.Add(ErrorCode.ERR_RefStructInterfaceImpl, location, this, baseType);
}
if (baseType.ContainsDynamic())
{
diagnostics.Add(ErrorCode.ERR_DeriveFromConstructedDynamic, location, this, baseType);
}
localInterfaces.Add((NamedTypeSymbol)baseType);
continue;
case TypeKind.Class:
if (TypeKind == TypeKind.Class)
{
if ((object)localBase == null)
{
localBase = (NamedTypeSymbol)baseType;
diagnostics.Add(ErrorCode.ERR_BaseClassMustBeFirst, location, baseType);
continue;
}
else
{
diagnostics.Add(ErrorCode.ERR_NoMultipleInheritance, location, this, localBase, baseType);
continue;
}
}
goto default;
case TypeKind.TypeParameter:
diagnostics.Add(ErrorCode.ERR_DerivingFromATyVar, location, baseType);
continue;
case TypeKind.Error:
// put the error type in the interface list so we don't lose track of it
localInterfaces.Add((NamedTypeSymbol)baseType);
continue;
case TypeKind.Dynamic:
diagnostics.Add(ErrorCode.ERR_DeriveFromDynamic, location, this);
continue;
case TypeKind.Submission:
throw ExceptionUtilities.UnexpectedValue(baseType.TypeKind);
default:
diagnostics.Add(ErrorCode.ERR_NonInterfaceInInterfaceList, location, baseType);
continue;
}
}
if (this.SpecialType == SpecialType.System_Object && ((object)localBase != null || localInterfaces.Count != 0))
{
var name = GetName(bases.Parent);
diagnostics.Add(ErrorCode.ERR_ObjectCantHaveBases, new SourceLocation(name));
}
return new Tuple<NamedTypeSymbol, ImmutableArray<NamedTypeSymbol>>(localBase, localInterfaces.ToImmutableAndFree());
void checkPrimaryConstructorBaseType(BaseTypeSyntax baseTypeSyntax, TypeSymbol baseType)
{
if (baseTypeSyntax is PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType &&
(!IsRecord || TypeKind != TypeKind.Class || baseType.TypeKind == TypeKind.Interface || ((RecordDeclarationSyntax)decl.SyntaxReference.GetSyntax()).ParameterList is null))
{
diagnostics.Add(ErrorCode.ERR_UnexpectedArgumentList, primaryConstructorBaseType.ArgumentList.Location);
}
}
}
/// <summary>
/// Returns true if the type cannot be used as an explicit base class.
/// </summary>
private static bool IsRestrictedBaseType(SpecialType specialType)
{
switch (specialType)
{
case SpecialType.System_Array:
case SpecialType.System_Enum:
case SpecialType.System_Delegate:
case SpecialType.System_MulticastDelegate:
case SpecialType.System_ValueType:
return true;
}
return false;
}
private ImmutableArray<NamedTypeSymbol> MakeAcyclicInterfaces(ConsList<TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics)
{
var typeKind = this.TypeKind;
if (typeKind == TypeKind.Enum)
{
Debug.Assert(GetDeclaredInterfaces(basesBeingResolved: null).IsEmpty, "Computation skipped for enums");
return ImmutableArray<NamedTypeSymbol>.Empty;
}
var declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved: basesBeingResolved);
bool isInterface = (typeKind == TypeKind.Interface);
ArrayBuilder<NamedTypeSymbol> result = isInterface ? ArrayBuilder<NamedTypeSymbol>.GetInstance() : null;
foreach (var t in declaredInterfaces)
{
if (isInterface)
{
if (BaseTypeAnalysis.TypeDependsOn(depends: t, on: this))
{
result.Add(new ExtendedErrorTypeSymbol(t, LookupResultKind.NotReferencable,
diagnostics.Add(ErrorCode.ERR_CycleInInterfaceInheritance, Locations[0], this, t)));
continue;
}
else
{
result.Add(t);
}
}
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
if (t.DeclaringCompilation != this.DeclaringCompilation)
{
t.AddUseSiteInfo(ref useSiteInfo);
foreach (var @interface in t.AllInterfacesNoUseSiteDiagnostics)
{
if (@interface.DeclaringCompilation != this.DeclaringCompilation)
{
@interface.AddUseSiteInfo(ref useSiteInfo);
}
}
}
diagnostics.Add(Locations[0], useSiteInfo);
}
return isInterface ? result.ToImmutableAndFree() : declaredInterfaces;
}
private NamedTypeSymbol MakeAcyclicBaseType(BindingDiagnosticBag diagnostics)
{
var typeKind = this.TypeKind;
var compilation = this.DeclaringCompilation;
NamedTypeSymbol declaredBase;
if (typeKind == TypeKind.Enum)
{
Debug.Assert((object)GetDeclaredBaseType(basesBeingResolved: null) == null, "Computation skipped for enums");
declaredBase = compilation.GetSpecialType(SpecialType.System_Enum);
}
else
{
declaredBase = GetDeclaredBaseType(basesBeingResolved: null);
}
if ((object)declaredBase == null)
{
switch (typeKind)
{
case TypeKind.Class:
if (this.SpecialType == SpecialType.System_Object)
{
return null;
}
declaredBase = compilation.GetSpecialType(SpecialType.System_Object);
break;
case TypeKind.Struct:
declaredBase = compilation.GetSpecialType(SpecialType.System_ValueType);
break;
case TypeKind.Interface:
return null;
case TypeKind.Delegate:
declaredBase = compilation.GetSpecialType(SpecialType.System_MulticastDelegate);
break;
default:
throw ExceptionUtilities.UnexpectedValue(typeKind);
}
}
if (BaseTypeAnalysis.TypeDependsOn(declaredBase, this))
{
return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable,
diagnostics.Add(ErrorCode.ERR_CircularBase, Locations[0], declaredBase, this));
}
this.SetKnownToHaveNoDeclaredBaseCycles();
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
NamedTypeSymbol current = declaredBase;
do
{
if (current.DeclaringCompilation == this.DeclaringCompilation)
{
break;
}
current.AddUseSiteInfo(ref useSiteInfo);
current = current.BaseTypeNoUseSiteDiagnostics;
}
while ((object)current != null);
diagnostics.Add(useSiteInfo.Diagnostics.IsNullOrEmpty() ? Location.None : (FindBaseRefSyntax(declaredBase) ?? Locations[0]), useSiteInfo);
return declaredBase;
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/VarianceTests.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.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class VarianceTests
Inherits BasicTestBase
<Fact>
Public Sub Disallowed1()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
End Sub
End Module
Class C124(Of In T, Out S)
End Class
Structure S124(Of In T, Out S)
End Structure
Interface I125(Of In T, Out S)
End Interface
Delegate Sub D126(Of In T, Out S)()
Class C125
Sub Goo(Of In T, Out S)()
End Sub
Function Bar(Of In T, Out S)() As Integer
Return 0
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom))
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class C124(Of In T, Out S)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class C124(Of In T, Out S)
~~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure S124(Of In T, Out S)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure S124(Of In T, Out S)
~~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Sub Goo(Of In T, Out S)()
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Sub Goo(Of In T, Out S)()
~~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Function Bar(Of In T, Out S)() As Integer
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Function Bar(Of In T, Out S)() As Integer
~~~
</expected>)
End Sub
<Fact>
Public Sub NestingInAnInterface1()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Interface I1(Of In T, Out S)
Interface I2(Of In T1, Out S1)
End Interface
Delegate Sub D1(Of In T1, Out S1)()
Class C1(Of In T1)
Class C2
End Class
Structure S1
End Structure
Enum E1
x
End Enum
Interface I3(Of In T2, Out S2)
End Interface
Delegate Sub D1(Of In T2, Out S2)()
End Class
Class C3
Class C4
End Class
Structure S2
End Structure
Enum E2
x
End Enum
Interface I4(Of In T1, Out S1)
End Interface
Delegate Sub D2(Of In T2, Out S2)()
End Class
Structure S3(Of In T1)
Class C5
End Class
Structure S4
End Structure
Enum E3
x
End Enum
Interface I5(Of In T2, Out S2)
End Interface
Delegate Sub D3(Of In T2, Out S2)()
End Structure
Structure S5
Class C6
End Class
Structure S5
End Structure
Enum E4
x
End Enum
Interface I6(Of In T2, Out S2)
End Interface
Delegate Sub D4(Of In T2, Out S2)()
End Structure
Enum E5
y
End Enum
Interface I7
Class C7
End Class
Structure S6
End Structure
Enum E6
x
End Enum
Interface I8(Of In T2, Out S2)
End Interface
Delegate Sub D5(Of In T2, Out S2)()
End Interface
End Interface
Interface I9
Class C8
End Class
Structure S7
End Structure
Enum E7
x
End Enum
Interface I10(Of In T2, Out S2)
End Interface
Delegate Sub D6(Of In T2, Out S2)()
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
Dim expected =
<expected>
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C1(Of In T1)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class C1(Of In T1)
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C3
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Structure S3(Of In T1)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure S3(Of In T1)
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Structure S5
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Enum E5
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C7
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Structure S6
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Enum E6
~~
</expected>
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
' Second time is intentional!
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<Fact>
Public Sub SyntheticEventDelegate1()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Interface I1(Of In T)
Event x1(y As Integer)
End Interface
Interface I2(Of Out T)
Event x2(y As Integer)
End Interface
Interface I3(Of T)
Event x3(y As Integer)
End Interface
Interface I4(Of In T)
Interface I5
Event x4(y As Integer)
End Interface
Class C1
Event x5(y As Integer)
End Class
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
Dim expected =
<expected>
BC36738: Event definitions with parameters are not allowed in an interface such as 'I1(Of T)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I1(Of T)'. For example, 'Event x1 As Action(Of ...)'.
Event x1(y As Integer)
~~~~~~~~~~~~~~~~~~~~~~
BC36738: Event definitions with parameters are not allowed in an interface such as 'I2(Of T)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I2(Of T)'. For example, 'Event x2 As Action(Of ...)'.
Event x2(y As Integer)
~~~~~~~~~~~~~~~~~~~~~~
BC36738: Event definitions with parameters are not allowed in an interface such as 'I4(Of T)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I4(Of T)'. For example, 'Event x4 As Action(Of ...)'.
Event x4(y As Integer)
~~~~~~~~~~~~~~~~~~~~~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C1
~~
</expected>
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
' Second time is intentional!
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<Fact>
Public Sub Consistency1()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Option Strict On
Imports System
Interface RW(Of Out T1, In T2) : End Interface
Interface R(Of Out T) : End Interface
Interface W(Of In T) : End Interface
Class Animal : End Class
Class Fish : Inherits Animal : End Class
Class Mammal : Inherits Animal : End Class
Class ChimeraFM : Implements R(Of Fish) : Implements R(Of Mammal) : End Class ' BC42333 "R(Of Mammal)", BC42333 "R(Of Fish)"
Delegate Sub D(Of In T1)(ByVal x As T1)
Class C(Of In T) 'BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Sub Test()
Dim r As R(Of Animal) = New ChimeraFM ' BC36737: Option Strict On does not allow implicit conversions from 'ChimeraFM' to 'R(Of Animal)' because the conversion is ambiguous.
End Sub
End Class
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Inherits RW(Of Tout, Tin) ' okay
Inherits W(Of Tout) ' BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Inherits R(Of Tin) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Sub f(ByVal x As Tin) ' okay
Function f() As Tout ' okay
Sub f(ByVal x As RW(Of Tin, Tout)) ' okay
Sub f(ByVal x As RW(Of RW(Of Tin, Tout), RW(Of Tout, Tin))) ' okay
Interface J : End Interface ' okay
Sub f36742(ByVal x As Tout) ' BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an Out type parameter.
Sub f36742arr(ByVal x As Tout()) ' BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an Out type parameter.
Function f36743() As Tin ' BC36743: Type 'Tin' cannot be used as a return type because 'Tin' is an In type parameter.
Sub f36749(ByRef x As Tout) ' BC36749: Type 'Tout' cannot be used in this context because In/Out type parameters cannot be used for ByRef parameter types, and 'Tout' is an Out type parameter.
Sub f36750(ByRef x As Tin) ' BC36750: Type 'Tin' cannot be used in this context because In/Out type parameters cannot be used for ByRef parameter types, and 'Tin' is an In type parameter.
Sub f36744(Of T As Tout)() ' BC36744: Type 'Tout' cannot be used as a generic type constraint because 'Tout' is an Out type parameter.
ReadOnly Property p36745() As Tin ' BC36745: Type 'Tin' cannot be used as a ReadOnly property type because 'Tin' is an In type parameter.
WriteOnly Property p36746() As Tout ' BC36746: Type 'Tout' cannot be used as a WriteOnly property type because 'Tout' is an Out type parameter.
Property p36747() As Tout ' BC36747: Type 'Tout' cannot be used as a property type in this context because 'Tout' is an Out type parameter and the property is not marked ReadOnly.
Property p36748() As Tin ' BC36748: Type 'Tin' cannot be used as a property type in this context because 'Tin' is an In type parameter and the property is not marked WriteOnly.
Function f36740() As TSout? ' BC36740: Type 'TSout' cannot be used in 'TSout?' because In/Out type parameters cannot be made nullable, and 'TSout' is an Out type parameter.
Function f36740b() As Nullable(Of TSout) ' BC36740: Type 'TSout' cannot be used in 'TSout?' because In/Out type parameters cannot be made nullable, and 'TSout' is an Out type parameter.
Sub f36741(ByVal x As TSin?) ' BC36741: Type 'TSin' cannot be used in 'TSin?' because In/Out type parameters cannot be made nullable, and 'TSin is an In type parameter.
Sub f36741b(ByVal x As Nullable(Of TSin)) ' BC36741: Type 'TSin' cannot be used in 'TSin?' because In/Out type parameters cannot be made nullable, and 'TSin is an In type parameter.
Sub f36724(ByVal x As R(Of Tout)) ' BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Sub f36725(ByVal x As W(Of Tin)) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Sub f36728(ByVal x As R(Of R(Of Tout))) ' BC36728: Type 'Tout' cannot be used in 'R(Of Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36729(ByVal x As W(Of R(Of Tin))) ' BC36729: Type 'Tin' cannot be used in 'R(Of Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub f36726(ByVal x As RW(Of Tout, Tout)) ' BC36726: Type 'Tout' cannot be used for the 'T1' in 'RW(Of T1,T2)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36727(ByVal x As RW(Of Tin, Tin)) ' BC36727: Type 'Tin' cannot be used for the 'T2' in 'RW(Of T1,T2)' in this context because 'Tin' is an 'In' type parameter.
Sub f36730(ByVal x As RW(Of RW(Of Tout, Tout), RW(Of Tout, Tin))) ' BC36730: Type 'Tout' cannot be used for the 'T1' of 'RW(Of T1,T2)' in 'RW(Of Tout,Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36731(ByVal x As RW(Of RW(Of Tin, Tin), RW(Of Tout, Tin))) ' BC36731: Type 'Tin' cannot be used for the 'T2' of 'RW(Of T1,T2)' in 'RW(Of Tin,Tin)' in this context because 'Tin' is an 'In' type parameter.
Event e36738() ' BC36738: Event definitions with parameters are not allowed in an interface such as 'I(Of Tout,Tin,TSout,TSin)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I(Of Tout,Tin,TSout,TSin)'. For example, 'Event e36738 As Action(Of ...)'.
Class C : End Class ' BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Event e As D(Of Tin) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter
Sub f36732(ByVal x As J) ' BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
Sub f36733(ByVal x As RW(Of J, Tout)) ' BC36733: Type 'J' cannot be used for the 'T1' in 'RW(Of T1,T2)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
Sub f36735(ByVal x As R(Of R(Of J))) ' BC36735: Type 'J' cannot be used in 'R(Of J)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
Sub f36736(ByVal x As RW(Of RW(Of J, Tout), RW(Of Tout, Tin))) ' BC36736: Type 'J' cannot be used for the 'T1' of 'RW(Of T1,T2)' in 'RW(Of J,Tout)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
Sub f36732_1(ByVal x As R(Of J))
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
Dim expected =
<expected>
BC42333: Interface 'R(Of Mammal)' is ambiguous with another implemented interface 'R(Of Fish)' due to the 'In' and 'Out' parameters in 'Interface R(Of Out T)'.
Class ChimeraFM : Implements R(Of Fish) : Implements R(Of Mammal) : End Class ' BC42333 "R(Of Mammal)", BC42333 "R(Of Fish)"
~~~~~~~~~~~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class C(Of In T) 'BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
~~
BC36737: Option Strict On does not allow implicit conversions from 'ChimeraFM' to 'R(Of Animal)' because the conversion is ambiguous.
Dim r As R(Of Animal) = New ChimeraFM ' BC36737: Option Strict On does not allow implicit conversions from 'ChimeraFM' to 'R(Of Animal)' because the conversion is ambiguous.
~~~~~~~~~~~~~
BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Inherits W(Of Tout) ' BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~
BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Inherits R(Of Tin) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~
BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an 'Out' type parameter.
Sub f36742(ByVal x As Tout) ' BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an Out type parameter.
~~~~
BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an 'Out' type parameter.
Sub f36742arr(ByVal x As Tout()) ' BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an Out type parameter.
~~~~~~
BC36743: Type 'Tin' cannot be used as a return type because 'Tin' is an 'In' type parameter.
Function f36743() As Tin ' BC36743: Type 'Tin' cannot be used as a return type because 'Tin' is an In type parameter.
~~~
BC36749: Type 'Tout' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and 'Tout' is an 'Out' type parameter.
Sub f36749(ByRef x As Tout) ' BC36749: Type 'Tout' cannot be used in this context because In/Out type parameters cannot be used for ByRef parameter types, and 'Tout' is an Out type parameter.
~~~~
BC36750: Type 'Tin' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and 'Tin' is an 'In' type parameter.
Sub f36750(ByRef x As Tin) ' BC36750: Type 'Tin' cannot be used in this context because In/Out type parameters cannot be used for ByRef parameter types, and 'Tin' is an In type parameter.
~~~
BC36744: Type 'Tout' cannot be used as a generic type constraint because 'Tout' is an 'Out' type parameter.
Sub f36744(Of T As Tout)() ' BC36744: Type 'Tout' cannot be used as a generic type constraint because 'Tout' is an Out type parameter.
~~~~
BC36745: Type 'Tin' cannot be used as a ReadOnly property type because 'Tin' is an 'In' type parameter.
ReadOnly Property p36745() As Tin ' BC36745: Type 'Tin' cannot be used as a ReadOnly property type because 'Tin' is an In type parameter.
~~~
BC36746: Type 'Tout' cannot be used as a WriteOnly property type because 'Tout' is an 'Out' type parameter.
WriteOnly Property p36746() As Tout ' BC36746: Type 'Tout' cannot be used as a WriteOnly property type because 'Tout' is an Out type parameter.
~~~~
BC36747: Type 'Tout' cannot be used as a property type in this context because 'Tout' is an 'Out' type parameter and the property is not marked ReadOnly.
Property p36747() As Tout ' BC36747: Type 'Tout' cannot be used as a property type in this context because 'Tout' is an Out type parameter and the property is not marked ReadOnly.
~~~~
BC36748: Type 'Tin' cannot be used as a property type in this context because 'Tin' is an 'In' type parameter and the property is not marked WriteOnly.
Property p36748() As Tin ' BC36748: Type 'Tin' cannot be used as a property type in this context because 'Tin' is an In type parameter and the property is not marked WriteOnly.
~~~
BC36740: Type 'TSout' cannot be used in 'TSout?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSout' is an 'Out' type parameter.
Function f36740() As TSout? ' BC36740: Type 'TSout' cannot be used in 'TSout?' because In/Out type parameters cannot be made nullable, and 'TSout' is an Out type parameter.
~~~~~~
BC36740: Type 'TSout' cannot be used in 'TSout?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSout' is an 'Out' type parameter.
Function f36740b() As Nullable(Of TSout) ' BC36740: Type 'TSout' cannot be used in 'TSout?' because In/Out type parameters cannot be made nullable, and 'TSout' is an Out type parameter.
~~~~~~~~~~~~~~~~~~
BC36741: Type 'TSin' cannot be used in 'TSin?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSin' is an 'In' type parameter.
Sub f36741(ByVal x As TSin?) ' BC36741: Type 'TSin' cannot be used in 'TSin?' because In/Out type parameters cannot be made nullable, and 'TSin is an In type parameter.
~~~~~
BC36741: Type 'TSin' cannot be used in 'TSin?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSin' is an 'In' type parameter.
Sub f36741b(ByVal x As Nullable(Of TSin)) ' BC36741: Type 'TSin' cannot be used in 'TSin?' because In/Out type parameters cannot be made nullable, and 'TSin is an In type parameter.
~~~~~~~~~~~~~~~~~
BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Sub f36724(ByVal x As R(Of Tout)) ' BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~
BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Sub f36725(ByVal x As W(Of Tin)) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~
BC36728: Type 'Tout' cannot be used in 'R(Of Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36728(ByVal x As R(Of R(Of Tout))) ' BC36728: Type 'Tout' cannot be used in 'R(Of Tout)' in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~~~~~~~
BC36729: Type 'Tin' cannot be used in 'R(Of Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub f36729(ByVal x As W(Of R(Of Tin))) ' BC36729: Type 'Tin' cannot be used in 'R(Of Tin)' in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~~~~~~~
BC36726: Type 'Tout' cannot be used for the 'T1' in 'RW(Of T1, T2)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36726(ByVal x As RW(Of Tout, Tout)) ' BC36726: Type 'Tout' cannot be used for the 'T1' in 'RW(Of T1,T2)' in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~~~~~~~~
BC36727: Type 'Tin' cannot be used for the 'T2' in 'RW(Of T1, T2)' in this context because 'Tin' is an 'In' type parameter.
Sub f36727(ByVal x As RW(Of Tin, Tin)) ' BC36727: Type 'Tin' cannot be used for the 'T2' in 'RW(Of T1,T2)' in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~~~~~~~
BC36730: Type 'Tout' cannot be used for the 'T1' of 'RW(Of T1, T2)' in 'RW(Of Tout, Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36730(ByVal x As RW(Of RW(Of Tout, Tout), RW(Of Tout, Tin))) ' BC36730: Type 'Tout' cannot be used for the 'T1' of 'RW(Of T1,T2)' in 'RW(Of Tout,Tout)' in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36731: Type 'Tin' cannot be used for the 'T2' of 'RW(Of T1, T2)' in 'RW(Of Tin, Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub f36731(ByVal x As RW(Of RW(Of Tin, Tin), RW(Of Tout, Tin))) ' BC36731: Type 'Tin' cannot be used for the 'T2' of 'RW(Of T1,T2)' in 'RW(Of Tin,Tin)' in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36738: Event definitions with parameters are not allowed in an interface such as 'I(Of Tout, Tin, TSout, TSin)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I(Of Tout, Tin, TSout, TSin)'. For example, 'Event e36738 As Action(Of ...)'.
Event e36738() ' BC36738: Event definitions with parameters are not allowed in an interface such as 'I(Of Tout,Tin,TSout,TSin)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I(Of Tout,Tin,TSout,TSin)'. For example, 'Event e36738 As Action(Of ...)'.
~~~~~~~~~~~~~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C : End Class ' BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
~
BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Event e As D(Of Tin) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter
~~~~~~~~~
BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36732(ByVal x As J) ' BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
~
BC36733: Type 'J' cannot be used for the 'T1' in 'RW(Of T1, T2)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36733(ByVal x As RW(Of J, Tout)) ' BC36733: Type 'J' cannot be used for the 'T1' in 'RW(Of T1,T2)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
~~~~~~~~~~~~~~
BC36735: Type 'J' cannot be used in 'R(Of I(Of Tout, Tin, TSout, TSin).J)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36735(ByVal x As R(Of R(Of J))) ' BC36735: Type 'J' cannot be used in 'R(Of J)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
~~~~~~~~~~~~~
BC36736: Type 'J' cannot be used for the 'T1' of 'RW(Of T1, T2)' in 'RW(Of I(Of Tout, Tin, TSout, TSin).J, Tout)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36736(ByVal x As RW(Of RW(Of J, Tout), RW(Of Tout, Tin))) ' BC36736: Type 'J' cannot be used for the 'T1' of 'RW(Of T1,T2)' in 'RW(Of J,Tout)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36732_1(ByVal x As R(Of J))
~~~~~~~
</expected>
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<Fact>
Public Sub Consistency2()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Delegate Function Test(Of In T, Out S)(x As S) As T
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
Dim expected =
<expected>
BC36742: Type 'S' cannot be used as a ByVal parameter type because 'S' is an 'Out' type parameter.
Delegate Function Test(Of In T, Out S)(x As S) As T
~
BC36743: Type 'T' cannot be used as a return type because 'T' is an 'In' type parameter.
Delegate Function Test(Of In T, Out S)(x As S) As T
~
</expected>
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<Fact>
Public Sub TypeInferenceInVariance()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Option Strict On
Class Animal : End Class
Class Mammal : Inherits Animal : End Class
Interface IReadOnly(Of Out T) : End Interface
Class Zoo(Of T) : Implements IReadOnly(Of T) : End Class
Delegate Function D(Of Out T)() As T
Module Module1
Sub f(Of T)(ByVal d1 As D(Of T), ByVal d2 As D(Of T))
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Dim a As New Animal, m As New Mammal
Dim za As New Zoo(Of Animal), zm As New Zoo(Of Mammal)
Dim ra As IReadOnly(Of Animal) = zm, rm As IReadOnly(Of Mammal) = zm
f(Function() 1, Function() 2) ' Int
f(Function() 1, Function() 1.1) ' Double
f(Function() a, Function() m) ' Animal
f(Function() za, Function() za) ' Zoo(Of Animal)
f(Function() za, Function() ra) ' IReadOnly(Of Animal)
f(Function() zm, Function() zm) ' Zoo(Of Mammal)
f(Function() zm, Function() ra) ' IReadOnly(Of Animal)
f(Function() zm, Function() rm) ' IReadOnly(Of Mammal)
f(Function() ra, Function() ra) ' IReadOnly(Of Animal)
f(Function() ra, Function() rm) ' IReadOnly(Of Animal)
f(Function() rm, Function() rm) ' IReadOnly(Of Mammal)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
Dim expected = <![CDATA[
System.Int32
System.Double
Animal
Zoo`1[Animal]
IReadOnly`1[Animal]
Zoo`1[Mammal]
IReadOnly`1[Animal]
IReadOnly`1[Mammal]
IReadOnly`1[Animal]
IReadOnly`1[Animal]
IReadOnly`1[Mammal]
]]>
CompileAndVerify(compilation, expected)
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.Globalization
Imports System.Text
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class VarianceTests
Inherits BasicTestBase
<Fact>
Public Sub Disallowed1()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
End Sub
End Module
Class C124(Of In T, Out S)
End Class
Structure S124(Of In T, Out S)
End Structure
Interface I125(Of In T, Out S)
End Interface
Delegate Sub D126(Of In T, Out S)()
Class C125
Sub Goo(Of In T, Out S)()
End Sub
Function Bar(Of In T, Out S)() As Integer
Return 0
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom))
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class C124(Of In T, Out S)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class C124(Of In T, Out S)
~~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure S124(Of In T, Out S)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure S124(Of In T, Out S)
~~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Sub Goo(Of In T, Out S)()
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Sub Goo(Of In T, Out S)()
~~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Function Bar(Of In T, Out S)() As Integer
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Function Bar(Of In T, Out S)() As Integer
~~~
</expected>)
End Sub
<Fact>
Public Sub NestingInAnInterface1()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Interface I1(Of In T, Out S)
Interface I2(Of In T1, Out S1)
End Interface
Delegate Sub D1(Of In T1, Out S1)()
Class C1(Of In T1)
Class C2
End Class
Structure S1
End Structure
Enum E1
x
End Enum
Interface I3(Of In T2, Out S2)
End Interface
Delegate Sub D1(Of In T2, Out S2)()
End Class
Class C3
Class C4
End Class
Structure S2
End Structure
Enum E2
x
End Enum
Interface I4(Of In T1, Out S1)
End Interface
Delegate Sub D2(Of In T2, Out S2)()
End Class
Structure S3(Of In T1)
Class C5
End Class
Structure S4
End Structure
Enum E3
x
End Enum
Interface I5(Of In T2, Out S2)
End Interface
Delegate Sub D3(Of In T2, Out S2)()
End Structure
Structure S5
Class C6
End Class
Structure S5
End Structure
Enum E4
x
End Enum
Interface I6(Of In T2, Out S2)
End Interface
Delegate Sub D4(Of In T2, Out S2)()
End Structure
Enum E5
y
End Enum
Interface I7
Class C7
End Class
Structure S6
End Structure
Enum E6
x
End Enum
Interface I8(Of In T2, Out S2)
End Interface
Delegate Sub D5(Of In T2, Out S2)()
End Interface
End Interface
Interface I9
Class C8
End Class
Structure S7
End Structure
Enum E7
x
End Enum
Interface I10(Of In T2, Out S2)
End Interface
Delegate Sub D6(Of In T2, Out S2)()
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
Dim expected =
<expected>
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C1(Of In T1)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class C1(Of In T1)
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C3
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Structure S3(Of In T1)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure S3(Of In T1)
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Structure S5
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Enum E5
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C7
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Structure S6
~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Enum E6
~~
</expected>
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
' Second time is intentional!
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<Fact>
Public Sub SyntheticEventDelegate1()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Interface I1(Of In T)
Event x1(y As Integer)
End Interface
Interface I2(Of Out T)
Event x2(y As Integer)
End Interface
Interface I3(Of T)
Event x3(y As Integer)
End Interface
Interface I4(Of In T)
Interface I5
Event x4(y As Integer)
End Interface
Class C1
Event x5(y As Integer)
End Class
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
Dim expected =
<expected>
BC36738: Event definitions with parameters are not allowed in an interface such as 'I1(Of T)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I1(Of T)'. For example, 'Event x1 As Action(Of ...)'.
Event x1(y As Integer)
~~~~~~~~~~~~~~~~~~~~~~
BC36738: Event definitions with parameters are not allowed in an interface such as 'I2(Of T)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I2(Of T)'. For example, 'Event x2 As Action(Of ...)'.
Event x2(y As Integer)
~~~~~~~~~~~~~~~~~~~~~~
BC36738: Event definitions with parameters are not allowed in an interface such as 'I4(Of T)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I4(Of T)'. For example, 'Event x4 As Action(Of ...)'.
Event x4(y As Integer)
~~~~~~~~~~~~~~~~~~~~~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C1
~~
</expected>
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
' Second time is intentional!
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<Fact>
Public Sub Consistency1()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Option Strict On
Imports System
Interface RW(Of Out T1, In T2) : End Interface
Interface R(Of Out T) : End Interface
Interface W(Of In T) : End Interface
Class Animal : End Class
Class Fish : Inherits Animal : End Class
Class Mammal : Inherits Animal : End Class
Class ChimeraFM : Implements R(Of Fish) : Implements R(Of Mammal) : End Class ' BC42333 "R(Of Mammal)", BC42333 "R(Of Fish)"
Delegate Sub D(Of In T1)(ByVal x As T1)
Class C(Of In T) 'BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Sub Test()
Dim r As R(Of Animal) = New ChimeraFM ' BC36737: Option Strict On does not allow implicit conversions from 'ChimeraFM' to 'R(Of Animal)' because the conversion is ambiguous.
End Sub
End Class
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Inherits RW(Of Tout, Tin) ' okay
Inherits W(Of Tout) ' BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Inherits R(Of Tin) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Sub f(ByVal x As Tin) ' okay
Function f() As Tout ' okay
Sub f(ByVal x As RW(Of Tin, Tout)) ' okay
Sub f(ByVal x As RW(Of RW(Of Tin, Tout), RW(Of Tout, Tin))) ' okay
Interface J : End Interface ' okay
Sub f36742(ByVal x As Tout) ' BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an Out type parameter.
Sub f36742arr(ByVal x As Tout()) ' BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an Out type parameter.
Function f36743() As Tin ' BC36743: Type 'Tin' cannot be used as a return type because 'Tin' is an In type parameter.
Sub f36749(ByRef x As Tout) ' BC36749: Type 'Tout' cannot be used in this context because In/Out type parameters cannot be used for ByRef parameter types, and 'Tout' is an Out type parameter.
Sub f36750(ByRef x As Tin) ' BC36750: Type 'Tin' cannot be used in this context because In/Out type parameters cannot be used for ByRef parameter types, and 'Tin' is an In type parameter.
Sub f36744(Of T As Tout)() ' BC36744: Type 'Tout' cannot be used as a generic type constraint because 'Tout' is an Out type parameter.
ReadOnly Property p36745() As Tin ' BC36745: Type 'Tin' cannot be used as a ReadOnly property type because 'Tin' is an In type parameter.
WriteOnly Property p36746() As Tout ' BC36746: Type 'Tout' cannot be used as a WriteOnly property type because 'Tout' is an Out type parameter.
Property p36747() As Tout ' BC36747: Type 'Tout' cannot be used as a property type in this context because 'Tout' is an Out type parameter and the property is not marked ReadOnly.
Property p36748() As Tin ' BC36748: Type 'Tin' cannot be used as a property type in this context because 'Tin' is an In type parameter and the property is not marked WriteOnly.
Function f36740() As TSout? ' BC36740: Type 'TSout' cannot be used in 'TSout?' because In/Out type parameters cannot be made nullable, and 'TSout' is an Out type parameter.
Function f36740b() As Nullable(Of TSout) ' BC36740: Type 'TSout' cannot be used in 'TSout?' because In/Out type parameters cannot be made nullable, and 'TSout' is an Out type parameter.
Sub f36741(ByVal x As TSin?) ' BC36741: Type 'TSin' cannot be used in 'TSin?' because In/Out type parameters cannot be made nullable, and 'TSin is an In type parameter.
Sub f36741b(ByVal x As Nullable(Of TSin)) ' BC36741: Type 'TSin' cannot be used in 'TSin?' because In/Out type parameters cannot be made nullable, and 'TSin is an In type parameter.
Sub f36724(ByVal x As R(Of Tout)) ' BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Sub f36725(ByVal x As W(Of Tin)) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Sub f36728(ByVal x As R(Of R(Of Tout))) ' BC36728: Type 'Tout' cannot be used in 'R(Of Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36729(ByVal x As W(Of R(Of Tin))) ' BC36729: Type 'Tin' cannot be used in 'R(Of Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub f36726(ByVal x As RW(Of Tout, Tout)) ' BC36726: Type 'Tout' cannot be used for the 'T1' in 'RW(Of T1,T2)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36727(ByVal x As RW(Of Tin, Tin)) ' BC36727: Type 'Tin' cannot be used for the 'T2' in 'RW(Of T1,T2)' in this context because 'Tin' is an 'In' type parameter.
Sub f36730(ByVal x As RW(Of RW(Of Tout, Tout), RW(Of Tout, Tin))) ' BC36730: Type 'Tout' cannot be used for the 'T1' of 'RW(Of T1,T2)' in 'RW(Of Tout,Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36731(ByVal x As RW(Of RW(Of Tin, Tin), RW(Of Tout, Tin))) ' BC36731: Type 'Tin' cannot be used for the 'T2' of 'RW(Of T1,T2)' in 'RW(Of Tin,Tin)' in this context because 'Tin' is an 'In' type parameter.
Event e36738() ' BC36738: Event definitions with parameters are not allowed in an interface such as 'I(Of Tout,Tin,TSout,TSin)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I(Of Tout,Tin,TSout,TSin)'. For example, 'Event e36738 As Action(Of ...)'.
Class C : End Class ' BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Event e As D(Of Tin) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter
Sub f36732(ByVal x As J) ' BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
Sub f36733(ByVal x As RW(Of J, Tout)) ' BC36733: Type 'J' cannot be used for the 'T1' in 'RW(Of T1,T2)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
Sub f36735(ByVal x As R(Of R(Of J))) ' BC36735: Type 'J' cannot be used in 'R(Of J)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
Sub f36736(ByVal x As RW(Of RW(Of J, Tout), RW(Of Tout, Tin))) ' BC36736: Type 'J' cannot be used for the 'T1' of 'RW(Of T1,T2)' in 'RW(Of J,Tout)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
Sub f36732_1(ByVal x As R(Of J))
End Interface
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
Dim expected =
<expected>
BC42333: Interface 'R(Of Mammal)' is ambiguous with another implemented interface 'R(Of Fish)' due to the 'In' and 'Out' parameters in 'Interface R(Of Out T)'.
Class ChimeraFM : Implements R(Of Fish) : Implements R(Of Mammal) : End Class ' BC42333 "R(Of Mammal)", BC42333 "R(Of Fish)"
~~~~~~~~~~~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class C(Of In T) 'BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
~~
BC36737: Option Strict On does not allow implicit conversions from 'ChimeraFM' to 'R(Of Animal)' because the conversion is ambiguous.
Dim r As R(Of Animal) = New ChimeraFM ' BC36737: Option Strict On does not allow implicit conversions from 'ChimeraFM' to 'R(Of Animal)' because the conversion is ambiguous.
~~~~~~~~~~~~~
BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Inherits W(Of Tout) ' BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~
BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Inherits R(Of Tin) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~
BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an 'Out' type parameter.
Sub f36742(ByVal x As Tout) ' BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an Out type parameter.
~~~~
BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an 'Out' type parameter.
Sub f36742arr(ByVal x As Tout()) ' BC36742: Type 'Tout' cannot be used as a ByVal parameter type because 'Tout' is an Out type parameter.
~~~~~~
BC36743: Type 'Tin' cannot be used as a return type because 'Tin' is an 'In' type parameter.
Function f36743() As Tin ' BC36743: Type 'Tin' cannot be used as a return type because 'Tin' is an In type parameter.
~~~
BC36749: Type 'Tout' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and 'Tout' is an 'Out' type parameter.
Sub f36749(ByRef x As Tout) ' BC36749: Type 'Tout' cannot be used in this context because In/Out type parameters cannot be used for ByRef parameter types, and 'Tout' is an Out type parameter.
~~~~
BC36750: Type 'Tin' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and 'Tin' is an 'In' type parameter.
Sub f36750(ByRef x As Tin) ' BC36750: Type 'Tin' cannot be used in this context because In/Out type parameters cannot be used for ByRef parameter types, and 'Tin' is an In type parameter.
~~~
BC36744: Type 'Tout' cannot be used as a generic type constraint because 'Tout' is an 'Out' type parameter.
Sub f36744(Of T As Tout)() ' BC36744: Type 'Tout' cannot be used as a generic type constraint because 'Tout' is an Out type parameter.
~~~~
BC36745: Type 'Tin' cannot be used as a ReadOnly property type because 'Tin' is an 'In' type parameter.
ReadOnly Property p36745() As Tin ' BC36745: Type 'Tin' cannot be used as a ReadOnly property type because 'Tin' is an In type parameter.
~~~
BC36746: Type 'Tout' cannot be used as a WriteOnly property type because 'Tout' is an 'Out' type parameter.
WriteOnly Property p36746() As Tout ' BC36746: Type 'Tout' cannot be used as a WriteOnly property type because 'Tout' is an Out type parameter.
~~~~
BC36747: Type 'Tout' cannot be used as a property type in this context because 'Tout' is an 'Out' type parameter and the property is not marked ReadOnly.
Property p36747() As Tout ' BC36747: Type 'Tout' cannot be used as a property type in this context because 'Tout' is an Out type parameter and the property is not marked ReadOnly.
~~~~
BC36748: Type 'Tin' cannot be used as a property type in this context because 'Tin' is an 'In' type parameter and the property is not marked WriteOnly.
Property p36748() As Tin ' BC36748: Type 'Tin' cannot be used as a property type in this context because 'Tin' is an In type parameter and the property is not marked WriteOnly.
~~~
BC36740: Type 'TSout' cannot be used in 'TSout?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSout' is an 'Out' type parameter.
Function f36740() As TSout? ' BC36740: Type 'TSout' cannot be used in 'TSout?' because In/Out type parameters cannot be made nullable, and 'TSout' is an Out type parameter.
~~~~~~
BC36740: Type 'TSout' cannot be used in 'TSout?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSout' is an 'Out' type parameter.
Function f36740b() As Nullable(Of TSout) ' BC36740: Type 'TSout' cannot be used in 'TSout?' because In/Out type parameters cannot be made nullable, and 'TSout' is an Out type parameter.
~~~~~~~~~~~~~~~~~~
BC36741: Type 'TSin' cannot be used in 'TSin?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSin' is an 'In' type parameter.
Sub f36741(ByVal x As TSin?) ' BC36741: Type 'TSin' cannot be used in 'TSin?' because In/Out type parameters cannot be made nullable, and 'TSin is an In type parameter.
~~~~~
BC36741: Type 'TSin' cannot be used in 'TSin?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSin' is an 'In' type parameter.
Sub f36741b(ByVal x As Nullable(Of TSin)) ' BC36741: Type 'TSin' cannot be used in 'TSin?' because In/Out type parameters cannot be made nullable, and 'TSin is an In type parameter.
~~~~~~~~~~~~~~~~~
BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Sub f36724(ByVal x As R(Of Tout)) ' BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~
BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Sub f36725(ByVal x As W(Of Tin)) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~
BC36728: Type 'Tout' cannot be used in 'R(Of Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36728(ByVal x As R(Of R(Of Tout))) ' BC36728: Type 'Tout' cannot be used in 'R(Of Tout)' in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~~~~~~~
BC36729: Type 'Tin' cannot be used in 'R(Of Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub f36729(ByVal x As W(Of R(Of Tin))) ' BC36729: Type 'Tin' cannot be used in 'R(Of Tin)' in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~~~~~~~
BC36726: Type 'Tout' cannot be used for the 'T1' in 'RW(Of T1, T2)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36726(ByVal x As RW(Of Tout, Tout)) ' BC36726: Type 'Tout' cannot be used for the 'T1' in 'RW(Of T1,T2)' in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~~~~~~~~
BC36727: Type 'Tin' cannot be used for the 'T2' in 'RW(Of T1, T2)' in this context because 'Tin' is an 'In' type parameter.
Sub f36727(ByVal x As RW(Of Tin, Tin)) ' BC36727: Type 'Tin' cannot be used for the 'T2' in 'RW(Of T1,T2)' in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~~~~~~~
BC36730: Type 'Tout' cannot be used for the 'T1' of 'RW(Of T1, T2)' in 'RW(Of Tout, Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub f36730(ByVal x As RW(Of RW(Of Tout, Tout), RW(Of Tout, Tin))) ' BC36730: Type 'Tout' cannot be used for the 'T1' of 'RW(Of T1,T2)' in 'RW(Of Tout,Tout)' in this context because 'Tout' is an 'Out' type parameter.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36731: Type 'Tin' cannot be used for the 'T2' of 'RW(Of T1, T2)' in 'RW(Of Tin, Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub f36731(ByVal x As RW(Of RW(Of Tin, Tin), RW(Of Tout, Tin))) ' BC36731: Type 'Tin' cannot be used for the 'T2' of 'RW(Of T1,T2)' in 'RW(Of Tin,Tin)' in this context because 'Tin' is an 'In' type parameter.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36738: Event definitions with parameters are not allowed in an interface such as 'I(Of Tout, Tin, TSout, TSin)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I(Of Tout, Tin, TSout, TSin)'. For example, 'Event e36738 As Action(Of ...)'.
Event e36738() ' BC36738: Event definitions with parameters are not allowed in an interface such as 'I(Of Tout,Tin,TSout,TSin)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I(Of Tout,Tin,TSout,TSin)'. For example, 'Event e36738 As Action(Of ...)'.
~~~~~~~~~~~~~~
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C : End Class ' BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
~
BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Event e As D(Of Tin) ' BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter
~~~~~~~~~
BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36732(ByVal x As J) ' BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
~
BC36733: Type 'J' cannot be used for the 'T1' in 'RW(Of T1, T2)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36733(ByVal x As RW(Of J, Tout)) ' BC36733: Type 'J' cannot be used for the 'T1' in 'RW(Of T1,T2)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
~~~~~~~~~~~~~~
BC36735: Type 'J' cannot be used in 'R(Of I(Of Tout, Tin, TSout, TSin).J)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36735(ByVal x As R(Of R(Of J))) ' BC36735: Type 'J' cannot be used in 'R(Of J)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
~~~~~~~~~~~~~
BC36736: Type 'J' cannot be used for the 'T1' of 'RW(Of T1, T2)' in 'RW(Of I(Of Tout, Tin, TSout, TSin).J, Tout)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36736(ByVal x As RW(Of RW(Of J, Tout), RW(Of Tout, Tin))) ' BC36736: Type 'J' cannot be used for the 'T1' of 'RW(Of T1,T2)' in 'RW(Of J,Tout)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout,Tin,TSout,TSin)', and 'I(Of Tout,Tin,TSout,TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout,Tin,TSout,TSin)'.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub f36732_1(ByVal x As R(Of J))
~~~~~~~
</expected>
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<Fact>
Public Sub Consistency2()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Delegate Function Test(Of In T, Out S)(x As S) As T
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
Dim expected =
<expected>
BC36742: Type 'S' cannot be used as a ByVal parameter type because 'S' is an 'Out' type parameter.
Delegate Function Test(Of In T, Out S)(x As S) As T
~
BC36743: Type 'T' cannot be used as a return type because 'T' is an 'In' type parameter.
Delegate Function Test(Of In T, Out S)(x As S) As T
~
</expected>
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<Fact>
Public Sub TypeInferenceInVariance()
Dim compilationDef =
<compilation name="SimpleTest1">
<file name="a.vb">
Option Strict On
Class Animal : End Class
Class Mammal : Inherits Animal : End Class
Interface IReadOnly(Of Out T) : End Interface
Class Zoo(Of T) : Implements IReadOnly(Of T) : End Class
Delegate Function D(Of Out T)() As T
Module Module1
Sub f(Of T)(ByVal d1 As D(Of T), ByVal d2 As D(Of T))
System.Console.WriteLine(GetType(T))
End Sub
Sub Main()
Dim a As New Animal, m As New Mammal
Dim za As New Zoo(Of Animal), zm As New Zoo(Of Mammal)
Dim ra As IReadOnly(Of Animal) = zm, rm As IReadOnly(Of Mammal) = zm
f(Function() 1, Function() 2) ' Int
f(Function() 1, Function() 1.1) ' Double
f(Function() a, Function() m) ' Animal
f(Function() za, Function() za) ' Zoo(Of Animal)
f(Function() za, Function() ra) ' IReadOnly(Of Animal)
f(Function() zm, Function() zm) ' Zoo(Of Mammal)
f(Function() zm, Function() ra) ' IReadOnly(Of Animal)
f(Function() zm, Function() rm) ' IReadOnly(Of Mammal)
f(Function() ra, Function() ra) ' IReadOnly(Of Animal)
f(Function() ra, Function() rm) ' IReadOnly(Of Animal)
f(Function() rm, Function() rm) ' IReadOnly(Of Mammal)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On))
Dim expected = <![CDATA[
System.Int32
System.Double
Animal
Zoo`1[Animal]
IReadOnly`1[Animal]
Zoo`1[Mammal]
IReadOnly`1[Animal]
IReadOnly`1[Mammal]
IReadOnly`1[Animal]
IReadOnly`1[Animal]
IReadOnly`1[Mammal]
]]>
CompileAndVerify(compilation, expected)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzerItem/AnalyzerItemSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal class AnalyzerItemSource : IAttachedCollectionSource, INotifyPropertyChanged
{
private readonly AnalyzersFolderItem _analyzersFolder;
private readonly IAnalyzersCommandHandler _commandHandler;
private IReadOnlyCollection<AnalyzerReference> _analyzerReferences;
private BulkObservableCollection<AnalyzerItem> _analyzerItems;
public event PropertyChangedEventHandler PropertyChanged;
public AnalyzerItemSource(AnalyzersFolderItem analyzersFolder, IAnalyzersCommandHandler commandHandler)
{
_analyzersFolder = analyzersFolder;
_commandHandler = commandHandler;
_analyzersFolder.Workspace.WorkspaceChanged += Workspace_WorkspaceChanged;
}
private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
UpdateAnalyzers();
break;
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
_analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectChanged:
if (e.ProjectId == _analyzersFolder.ProjectId)
{
UpdateAnalyzers();
}
break;
case WorkspaceChangeKind.ProjectRemoved:
if (e.ProjectId == _analyzersFolder.ProjectId)
{
_analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
}
break;
}
}
private void UpdateAnalyzers()
{
if (_analyzerItems == null)
{
// The set of AnalyzerItems hasn't been realized yet. Just signal that HasItems
// may have changed.
NotifyPropertyChanged(nameof(HasItems));
return;
}
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null &&
project.AnalyzerReferences != _analyzerReferences)
{
_analyzerReferences = project.AnalyzerReferences;
_analyzerItems.BeginBulkOperation();
var itemsToRemove = _analyzerItems
.Where(item => !_analyzerReferences.Contains(item.AnalyzerReference))
.ToArray();
var referencesToAdd = GetFilteredAnalyzers(_analyzerReferences, project)
.Where(r => !_analyzerItems.Any(item => item.AnalyzerReference == r))
.ToArray();
foreach (var item in itemsToRemove)
{
_analyzerItems.Remove(item);
}
foreach (var reference in referencesToAdd)
{
_analyzerItems.Add(new AnalyzerItem(_analyzersFolder, reference, _commandHandler.AnalyzerContextMenuController));
}
var sorted = _analyzerItems.OrderBy(item => item.AnalyzerReference.Display).ToArray();
for (var i = 0; i < sorted.Length; i++)
{
_analyzerItems.Move(_analyzerItems.IndexOf(sorted[i]), i);
}
_analyzerItems.EndBulkOperation();
NotifyPropertyChanged(nameof(HasItems));
}
}
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public bool HasItems
{
get
{
if (_analyzerItems != null)
{
return _analyzerItems.Count > 0;
}
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null)
{
return project.AnalyzerReferences.Count > 0;
}
return false;
}
}
public IEnumerable Items
{
get
{
if (_analyzerItems == null)
{
_analyzerItems = new BulkObservableCollection<AnalyzerItem>();
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null)
{
_analyzerReferences = project.AnalyzerReferences;
var initialSet = GetFilteredAnalyzers(_analyzerReferences, project)
.OrderBy(ar => ar.Display)
.Select(ar => new AnalyzerItem(_analyzersFolder, ar, _commandHandler.AnalyzerContextMenuController));
_analyzerItems.AddRange(initialSet);
}
}
Logger.Log(
FunctionId.SolutionExplorer_AnalyzerItemSource_GetItems,
KeyValueLogMessage.Create(m => m["Count"] = _analyzerItems.Count));
return _analyzerItems;
}
}
public object SourceItem
{
get
{
return _analyzersFolder;
}
}
private ImmutableHashSet<string> GetAnalyzersWithLoadErrors()
{
if (_analyzersFolder.Workspace is VisualStudioWorkspaceImpl)
{
/*
var vsProject = vsWorkspace.DeferredState?.ProjectTracker.GetProject(_analyzersFolder.ProjectId);
var vsAnalyzersMap = vsProject?.GetProjectAnalyzersMap();
if (vsAnalyzersMap != null)
{
return vsAnalyzersMap.Where(kvp => kvp.Value.HasLoadErrors).Select(kvp => kvp.Key).ToImmutableHashSet();
}
*/
}
return ImmutableHashSet<string>.Empty;
}
private ImmutableArray<AnalyzerReference> GetFilteredAnalyzers(IEnumerable<AnalyzerReference> analyzerReferences, Project project)
{
var analyzersWithLoadErrors = GetAnalyzersWithLoadErrors();
// Filter out analyzer dependencies which have no diagnostic analyzers, but still retain the unresolved analyzers and analyzers with load errors.
var builder = ArrayBuilder<AnalyzerReference>.GetInstance();
foreach (var analyzerReference in analyzerReferences)
{
// Analyzer dependency:
// 1. Must be an Analyzer file reference (we don't understand other analyzer dependencies).
// 2. Mush have no diagnostic analyzers.
// 3. Must have no source generators.
// 4. Must have non-null full path.
// 5. Must not have any assembly or analyzer load failures.
if (analyzerReference is AnalyzerFileReference &&
analyzerReference.GetAnalyzers(project.Language).IsDefaultOrEmpty &&
analyzerReference.GetGenerators(project.Language).IsDefaultOrEmpty &&
analyzerReference.FullPath != null &&
!analyzersWithLoadErrors.Contains(analyzerReference.FullPath))
{
continue;
}
builder.Add(analyzerReference);
}
return builder.ToImmutableAndFree();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal class AnalyzerItemSource : IAttachedCollectionSource, INotifyPropertyChanged
{
private readonly AnalyzersFolderItem _analyzersFolder;
private readonly IAnalyzersCommandHandler _commandHandler;
private IReadOnlyCollection<AnalyzerReference> _analyzerReferences;
private BulkObservableCollection<AnalyzerItem> _analyzerItems;
public event PropertyChangedEventHandler PropertyChanged;
public AnalyzerItemSource(AnalyzersFolderItem analyzersFolder, IAnalyzersCommandHandler commandHandler)
{
_analyzersFolder = analyzersFolder;
_commandHandler = commandHandler;
_analyzersFolder.Workspace.WorkspaceChanged += Workspace_WorkspaceChanged;
}
private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
UpdateAnalyzers();
break;
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
_analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectChanged:
if (e.ProjectId == _analyzersFolder.ProjectId)
{
UpdateAnalyzers();
}
break;
case WorkspaceChangeKind.ProjectRemoved:
if (e.ProjectId == _analyzersFolder.ProjectId)
{
_analyzersFolder.Workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
}
break;
}
}
private void UpdateAnalyzers()
{
if (_analyzerItems == null)
{
// The set of AnalyzerItems hasn't been realized yet. Just signal that HasItems
// may have changed.
NotifyPropertyChanged(nameof(HasItems));
return;
}
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null &&
project.AnalyzerReferences != _analyzerReferences)
{
_analyzerReferences = project.AnalyzerReferences;
_analyzerItems.BeginBulkOperation();
var itemsToRemove = _analyzerItems
.Where(item => !_analyzerReferences.Contains(item.AnalyzerReference))
.ToArray();
var referencesToAdd = GetFilteredAnalyzers(_analyzerReferences, project)
.Where(r => !_analyzerItems.Any(item => item.AnalyzerReference == r))
.ToArray();
foreach (var item in itemsToRemove)
{
_analyzerItems.Remove(item);
}
foreach (var reference in referencesToAdd)
{
_analyzerItems.Add(new AnalyzerItem(_analyzersFolder, reference, _commandHandler.AnalyzerContextMenuController));
}
var sorted = _analyzerItems.OrderBy(item => item.AnalyzerReference.Display).ToArray();
for (var i = 0; i < sorted.Length; i++)
{
_analyzerItems.Move(_analyzerItems.IndexOf(sorted[i]), i);
}
_analyzerItems.EndBulkOperation();
NotifyPropertyChanged(nameof(HasItems));
}
}
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public bool HasItems
{
get
{
if (_analyzerItems != null)
{
return _analyzerItems.Count > 0;
}
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null)
{
return project.AnalyzerReferences.Count > 0;
}
return false;
}
}
public IEnumerable Items
{
get
{
if (_analyzerItems == null)
{
_analyzerItems = new BulkObservableCollection<AnalyzerItem>();
var project = _analyzersFolder.Workspace
.CurrentSolution
.GetProject(_analyzersFolder.ProjectId);
if (project != null)
{
_analyzerReferences = project.AnalyzerReferences;
var initialSet = GetFilteredAnalyzers(_analyzerReferences, project)
.OrderBy(ar => ar.Display)
.Select(ar => new AnalyzerItem(_analyzersFolder, ar, _commandHandler.AnalyzerContextMenuController));
_analyzerItems.AddRange(initialSet);
}
}
Logger.Log(
FunctionId.SolutionExplorer_AnalyzerItemSource_GetItems,
KeyValueLogMessage.Create(m => m["Count"] = _analyzerItems.Count));
return _analyzerItems;
}
}
public object SourceItem
{
get
{
return _analyzersFolder;
}
}
private ImmutableHashSet<string> GetAnalyzersWithLoadErrors()
{
if (_analyzersFolder.Workspace is VisualStudioWorkspaceImpl)
{
/*
var vsProject = vsWorkspace.DeferredState?.ProjectTracker.GetProject(_analyzersFolder.ProjectId);
var vsAnalyzersMap = vsProject?.GetProjectAnalyzersMap();
if (vsAnalyzersMap != null)
{
return vsAnalyzersMap.Where(kvp => kvp.Value.HasLoadErrors).Select(kvp => kvp.Key).ToImmutableHashSet();
}
*/
}
return ImmutableHashSet<string>.Empty;
}
private ImmutableArray<AnalyzerReference> GetFilteredAnalyzers(IEnumerable<AnalyzerReference> analyzerReferences, Project project)
{
var analyzersWithLoadErrors = GetAnalyzersWithLoadErrors();
// Filter out analyzer dependencies which have no diagnostic analyzers, but still retain the unresolved analyzers and analyzers with load errors.
var builder = ArrayBuilder<AnalyzerReference>.GetInstance();
foreach (var analyzerReference in analyzerReferences)
{
// Analyzer dependency:
// 1. Must be an Analyzer file reference (we don't understand other analyzer dependencies).
// 2. Mush have no diagnostic analyzers.
// 3. Must have no source generators.
// 4. Must have non-null full path.
// 5. Must not have any assembly or analyzer load failures.
if (analyzerReference is AnalyzerFileReference &&
analyzerReference.GetAnalyzers(project.Language).IsDefaultOrEmpty &&
analyzerReference.GetGenerators(project.Language).IsDefaultOrEmpty &&
analyzerReference.FullPath != null &&
!analyzersWithLoadErrors.Contains(analyzerReference.FullPath))
{
continue;
}
builder.Add(analyzerReference);
}
return builder.ToImmutableAndFree();
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_XmlDoc.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.UnitTests.IntelliSense
<[UseExportProvider]>
Public Class VisualBasicCompletionCommandHandlerTests_XmlDoc
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummary() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendReturn()
Await state.AssertNoCompletionSession()
Await state.AssertLineTextAroundCaret(" ''' summary", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummaryOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' summary$$
Await state.AssertLineTextAroundCaret(" ''' summary", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummaryOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' summary>$$
Await state.AssertLineTextAroundCaret(" ''' summary>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummary() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <summary$$
Await state.AssertLineTextAroundCaret(" ''' <summary", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummaryOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' <summary$$
Await state.AssertLineTextAroundCaret(" ''' <summary", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummaryOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <summary>$$
Await state.AssertLineTextAroundCaret(" ''' <summary>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitRemarksOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("rema")
Await state.AssertSelectedCompletionItem(displayText:="remarks")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' remarks>$$
Await state.AssertLineTextAroundCaret(" ''' remarks>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitRemarksOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("rema")
Await state.AssertSelectedCompletionItem(displayText:="remarks")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <remarks>$$
Await state.AssertLineTextAroundCaret(" ''' <remarks>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitReturnsOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Function Goo() As Integer
End Function
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("retur")
Await state.AssertSelectedCompletionItem(displayText:="returns")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' returns>$$
Await state.AssertLineTextAroundCaret(" ''' returns>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitReturnsOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Function Goo() As Integer
End Function
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("retur")
Await state.AssertSelectedCompletionItem(displayText:="returns")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <returns>$$
Await state.AssertLineTextAroundCaret(" ''' <returns>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitExampleOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("examp")
Await state.AssertSelectedCompletionItem(displayText:="example")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' example>$$
Await state.AssertLineTextAroundCaret(" ''' example>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitExampleOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("examp")
Await state.AssertSelectedCompletionItem(displayText:="example")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <example>$$
Await state.AssertLineTextAroundCaret(" ''' <example>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitExceptionNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("except")
Await state.AssertSelectedCompletionItem(displayText:="exception")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <exception cref="$$"
Await state.AssertLineTextAroundCaret(" ''' <exception cref=""", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitExceptionOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("except")
Await state.AssertSelectedCompletionItem(displayText:="exception")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <exception cref=">$$"
Await state.AssertLineTextAroundCaret(" ''' <exception cref="">", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitCommentNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("!--")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <!--$$-->
Await state.AssertLineTextAroundCaret(" ''' <!--", "-->")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitCommentOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("!--")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <!-->$$-->
Await state.AssertLineTextAroundCaret(" ''' <!-->", "-->")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitCdataNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("![CDATA[")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <![CDATA[$$]]>
Await state.AssertLineTextAroundCaret(" ''' <![CDATA[", "]]>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitCdataOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("![CDATA[")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <![CDATA[>$$]]>
Await state.AssertLineTextAroundCaret(" ''' <![CDATA[>", "]]>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitIncludeNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("inclu")
Await state.AssertSelectedCompletionItem(displayText:="include")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <include file='$$' path='[@name=""]'/>
Await state.AssertLineTextAroundCaret(" ''' <include file='", "' path='[@name=""""]'/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitIncludeOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("inclu")
Await state.AssertSelectedCompletionItem(displayText:="include")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <include file='>$$' path='[@name=""]'/>
Await state.AssertLineTextAroundCaret(" ''' <include file='>", "' path='[@name=""""]'/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitPermissionNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("permiss")
Await state.AssertSelectedCompletionItem(displayText:="permission")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <permission cref="$$"
Await state.AssertLineTextAroundCaret(" ''' <permission cref=""", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitPermissionOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("permiss")
Await state.AssertSelectedCompletionItem(displayText:="permission")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <permission cref=">$$"
Await state.AssertLineTextAroundCaret(" ''' <permission cref="">", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSeeNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <see cref="$$"/>
Await state.AssertLineTextAroundCaret(" ''' <see cref=""", """/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeeOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <see cref=">$$"/>
Await state.AssertLineTextAroundCaret(" ''' <see cref="">", """/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeeOnSpace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' <summary>
''' $$
''' </summary>
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendTypeChars(" ")
' ''' <see cref="$$"/>
Await state.AssertLineTextAroundCaret(" ''' <see cref=""", """/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithNothingKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Nothing")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithSharedKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Shared")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithOverridableKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Overridable", unique:=False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithTrueKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("True")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithFalseKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("False")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithMustInheritKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("MustInherit")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithNotOverridableKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("NotOverridable")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithAsyncKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Async")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithAwaitKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Await")
End Function
Private Shared Async Function InvokeWithKeywordCommitSeeLangword(keyword As String, Optional unique As Boolean = True) As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' <summary>
''' $$
''' </summary>
Sub Goo()
End Sub
End Class
]]></Document>)
' Omit the last letter of the keyword to make it easier to diagnose failures (inserted the wrong text,
' or did not insert text at all).
state.SendTypeChars(keyword.Substring(0, keyword.Length - 1))
state.SendInvokeCompletionList()
If unique Then
Await state.SendCommitUniqueCompletionListItemAsync()
Else
Await state.AssertSelectedCompletionItem(displayText:=keyword)
state.SendTab()
End If
Await state.AssertNoCompletionSession()
' ''' <see langword="keyword"/>$$
Await state.AssertLineTextAroundCaret(" ''' <see langword=""" + keyword + """/>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSeealsoNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("seeal")
Await state.AssertSelectedCompletionItem(displayText:="seealso")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <seealso cref="$$"/>
Await state.AssertLineTextAroundCaret(" ''' <seealso cref=""", """/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeealsoOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("seeal")
Await state.AssertSelectedCompletionItem(displayText:="seealso")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <seealso cref=">$$"/>
Await state.AssertLineTextAroundCaret(" ''' <seealso cref="">", """/>")
End Using
End Function
<WorkItem(623219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623219")>
<WorkItem(746919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/746919")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParam() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <param$$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngleOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngleOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' param name="bar">$$
Await state.AssertLineTextAroundCaret(" ''' param name=""bar"">", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParam() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParamOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' <param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParamOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <param name="bar">$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""bar"">", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" ''' typeparam name=""T""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngleOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" ''' typeparam name=""T""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngleOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' typeparam name="T">$$
Await state.AssertLineTextAroundCaret(" ''' typeparam name=""T"">", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparam() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" ''' <typeparam name=""T""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparamOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' <typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" ''' <typeparam name=""T""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparamOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <typeparam name="T">$$
Await state.AssertLineTextAroundCaret(" ''' <typeparam name=""T"">", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitList() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <summary>
''' $$
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("lis")
Await state.AssertSelectedCompletionItem(displayText:="list")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <list type="$$"
Await state.AssertLineTextAroundCaret(" ''' <list type=""", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitListOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <summary>
''' $$
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("lis")
Await state.AssertSelectedCompletionItem(displayText:="list")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <list type=">$$"
Await state.AssertLineTextAroundCaret(" ''' <list type="">", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <$$
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <summary>$$
Await state.AssertLineTextAroundCaret(" ''' <summary>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion2() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <$$
''' <remarks></remarks>
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <summary>$$
Await state.AssertLineTextAroundCaret(" ''' <summary>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion3() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <$$
''' <remarks>
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <summary>$$
Await state.AssertLineTextAroundCaret(" ''' <summary>", "")
End Using
End Function
<WorkItem(638653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638653")>
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/21481"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AllowTypingDoubleQuote() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <param$$
Sub Goo(Of T)(bar as T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(" name=""")
' ''' <param name="$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""", "")
' Because the item contains a double quote, the completionImplementation list should still be present with the same selection
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
End Using
End Function
<WorkItem(638653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638653")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AllowTypingSpace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <param$$
Sub Goo(Of T)(bar as T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(" ")
' ''' <param $$
Await state.AssertLineTextAroundCaret(" ''' <param ", "")
' Because the item contains a space, the completionImplementation list should still be present with the same selection
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
<[UseExportProvider]>
Public Class VisualBasicCompletionCommandHandlerTests_XmlDoc
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummary() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendReturn()
Await state.AssertNoCompletionSession()
Await state.AssertLineTextAroundCaret(" ''' summary", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummaryOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' summary$$
Await state.AssertLineTextAroundCaret(" ''' summary", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSummaryOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' summary>$$
Await state.AssertLineTextAroundCaret(" ''' summary>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummary() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <summary$$
Await state.AssertLineTextAroundCaret(" ''' <summary", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummaryOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' <summary$$
Await state.AssertLineTextAroundCaret(" ''' <summary", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSummaryOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("summ")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <summary>$$
Await state.AssertLineTextAroundCaret(" ''' <summary>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitRemarksOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("rema")
Await state.AssertSelectedCompletionItem(displayText:="remarks")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' remarks>$$
Await state.AssertLineTextAroundCaret(" ''' remarks>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitRemarksOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("rema")
Await state.AssertSelectedCompletionItem(displayText:="remarks")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <remarks>$$
Await state.AssertLineTextAroundCaret(" ''' <remarks>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitReturnsOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Function Goo() As Integer
End Function
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("retur")
Await state.AssertSelectedCompletionItem(displayText:="returns")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' returns>$$
Await state.AssertLineTextAroundCaret(" ''' returns>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitReturnsOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Function Goo() As Integer
End Function
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("retur")
Await state.AssertSelectedCompletionItem(displayText:="returns")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <returns>$$
Await state.AssertLineTextAroundCaret(" ''' <returns>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitExampleOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("examp")
Await state.AssertSelectedCompletionItem(displayText:="example")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' example>$$
Await state.AssertLineTextAroundCaret(" ''' example>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitExampleOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("examp")
Await state.AssertSelectedCompletionItem(displayText:="example")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <example>$$
Await state.AssertLineTextAroundCaret(" ''' <example>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitExceptionNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("except")
Await state.AssertSelectedCompletionItem(displayText:="exception")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <exception cref="$$"
Await state.AssertLineTextAroundCaret(" ''' <exception cref=""", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitExceptionOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("except")
Await state.AssertSelectedCompletionItem(displayText:="exception")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <exception cref=">$$"
Await state.AssertLineTextAroundCaret(" ''' <exception cref="">", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitCommentNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("!--")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <!--$$-->
Await state.AssertLineTextAroundCaret(" ''' <!--", "-->")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitCommentOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("!--")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <!-->$$-->
Await state.AssertLineTextAroundCaret(" ''' <!-->", "-->")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitCdataNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("![CDATA[")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <![CDATA[$$]]>
Await state.AssertLineTextAroundCaret(" ''' <![CDATA[", "]]>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitCdataOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendSelectCompletionItem("![CDATA[")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <![CDATA[>$$]]>
Await state.AssertLineTextAroundCaret(" ''' <![CDATA[>", "]]>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitIncludeNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("inclu")
Await state.AssertSelectedCompletionItem(displayText:="include")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <include file='$$' path='[@name=""]'/>
Await state.AssertLineTextAroundCaret(" ''' <include file='", "' path='[@name=""""]'/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitIncludeOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("inclu")
Await state.AssertSelectedCompletionItem(displayText:="include")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <include file='>$$' path='[@name=""]'/>
Await state.AssertLineTextAroundCaret(" ''' <include file='>", "' path='[@name=""""]'/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitPermissionNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("permiss")
Await state.AssertSelectedCompletionItem(displayText:="permission")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <permission cref="$$"
Await state.AssertLineTextAroundCaret(" ''' <permission cref=""", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitPermissionOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("permiss")
Await state.AssertSelectedCompletionItem(displayText:="permission")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <permission cref=">$$"
Await state.AssertLineTextAroundCaret(" ''' <permission cref="">", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSeeNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <see cref="$$"/>
Await state.AssertLineTextAroundCaret(" ''' <see cref=""", """/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeeOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <see cref=">$$"/>
Await state.AssertLineTextAroundCaret(" ''' <see cref="">", """/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeeOnSpace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' <summary>
''' $$
''' </summary>
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("see")
Await state.AssertSelectedCompletionItem(displayText:="see")
state.SendTypeChars(" ")
' ''' <see cref="$$"/>
Await state.AssertLineTextAroundCaret(" ''' <see cref=""", """/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithNothingKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Nothing")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithSharedKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Shared")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithOverridableKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Overridable", unique:=False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithTrueKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("True")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithFalseKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("False")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithMustInheritKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("MustInherit")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithNotOverridableKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("NotOverridable")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithAsyncKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Async")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Function InvokeWithAwaitKeywordCommitSeeLangword() As Task
Return InvokeWithKeywordCommitSeeLangword("Await")
End Function
Private Shared Async Function InvokeWithKeywordCommitSeeLangword(keyword As String, Optional unique As Boolean = True) As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' <summary>
''' $$
''' </summary>
Sub Goo()
End Sub
End Class
]]></Document>)
' Omit the last letter of the keyword to make it easier to diagnose failures (inserted the wrong text,
' or did not insert text at all).
state.SendTypeChars(keyword.Substring(0, keyword.Length - 1))
state.SendInvokeCompletionList()
If unique Then
Await state.SendCommitUniqueCompletionListItemAsync()
Else
Await state.AssertSelectedCompletionItem(displayText:=keyword)
state.SendTab()
End If
Await state.AssertNoCompletionSession()
' ''' <see langword="keyword"/>$$
Await state.AssertLineTextAroundCaret(" ''' <see langword=""" + keyword + """/>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitSeealsoNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("seeal")
Await state.AssertSelectedCompletionItem(displayText:="seealso")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <seealso cref="$$"/>
Await state.AssertLineTextAroundCaret(" ''' <seealso cref=""", """/>")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitSeealsoOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C
''' $$
Sub Goo()
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("seeal")
Await state.AssertSelectedCompletionItem(displayText:="seealso")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <seealso cref=">$$"/>
Await state.AssertLineTextAroundCaret(" ''' <seealso cref="">", """/>")
End Using
End Function
<WorkItem(623219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623219")>
<WorkItem(746919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/746919")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParam() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <param$$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngleOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitParamNoOpenAngleOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' param name="bar">$$
Await state.AssertLineTextAroundCaret(" ''' param name=""bar"">", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParam() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParamOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' <param name="bar"$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""bar""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitParamOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("param")
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <param name="bar">$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""bar"">", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" ''' typeparam name=""T""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngleOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" ''' typeparam name=""T""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitTypeparamNoOpenAngleOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' typeparam name="T">$$
Await state.AssertLineTextAroundCaret(" ''' typeparam name=""T"">", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparam() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" ''' <typeparam name=""T""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparamOnTab() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTab()
Await state.AssertNoCompletionSession()
' ''' <typeparam name="T"$$
Await state.AssertLineTextAroundCaret(" ''' <typeparam name=""T""", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function InvokeWithOpenAngleCommitTypeparamOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' $$
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendTypeChars("<")
Await state.AssertCompletionSession()
state.SendTypeChars("typepara")
Await state.AssertSelectedCompletionItem(displayText:="typeparam name=""T""")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <typeparam name="T">$$
Await state.AssertLineTextAroundCaret(" ''' <typeparam name=""T"">", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitList() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <summary>
''' $$
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("lis")
Await state.AssertSelectedCompletionItem(displayText:="list")
state.SendReturn()
Await state.AssertNoCompletionSession()
' ''' <list type="$$"
Await state.AssertLineTextAroundCaret(" ''' <list type=""", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function CommitListOnCloseAngle() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <summary>
''' $$
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("lis")
Await state.AssertSelectedCompletionItem(displayText:="list")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <list type=">$$"
Await state.AssertLineTextAroundCaret(" ''' <list type="">", """")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion1() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <$$
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <summary>$$
Await state.AssertLineTextAroundCaret(" ''' <summary>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion2() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <$$
''' <remarks></remarks>
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <summary>$$
Await state.AssertLineTextAroundCaret(" ''' <summary>", "")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTagCompletion3() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <$$
''' <remarks>
''' </summary>
Sub Goo(Of T)(bar As T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("summa")
Await state.AssertSelectedCompletionItem(displayText:="summary")
state.SendTypeChars(">")
Await state.AssertNoCompletionSession()
' ''' <summary>$$
Await state.AssertLineTextAroundCaret(" ''' <summary>", "")
End Using
End Function
<WorkItem(638653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638653")>
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/21481"), Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AllowTypingDoubleQuote() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <param$$
Sub Goo(Of T)(bar as T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(" name=""")
' ''' <param name="$$
Await state.AssertLineTextAroundCaret(" ''' <param name=""", "")
' Because the item contains a double quote, the completionImplementation list should still be present with the same selection
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
End Using
End Function
<WorkItem(638653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638653")>
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function AllowTypingSpace() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Class C(Of T)
''' <param$$
Sub Goo(Of T)(bar as T)
End Sub
End Class
]]></Document>)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
state.SendTypeChars(" ")
' ''' <param $$
Await state.AssertLineTextAroundCaret(" ''' <param ", "")
' Because the item contains a space, the completionImplementation list should still be present with the same selection
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem(displayText:="param name=""bar""")
End Using
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/VisualBasic/Portable/Errors/Errors.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.
'//-------------------------------------------------------------------------------------------------
'//
'// Error code and strings for Compiler errors
'//
'// ERRIDs should be defined in the following ranges:
'//
'// 500 - 999 - non localized ERRID (main DLL)
'// 30000 - 59999 - localized ERRID (intl DLL)
'//
'// The convention for naming ERRID's that take replacement strings is to give
'// them a number following the name (from 1-9) that indicates how many
'// arguments they expect.
'//
'// DO NOT USE ANY NUMBERS EXCEPT THOSE EXPLICITLY LISTED AS BEING AVAILABLE.
'// IF YOU REUSE A NUMBER, LOCALIZATION WILL BE SCREWED UP!
'//
'//-------------------------------------------------------------------------------------------------
' //-------------------------------------------------------------------------------------------------
' //
' //
' // Manages the parse and compile errors.
' //
' //-------------------------------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Enum ERRID
Void = InternalErrorCode.Void
Unknown = InternalErrorCode.Unknown
ERR_None = 0
' ERR_InitError = 2000 unused in Roslyn
ERR_FileNotFound = 2001
' WRN_FileAlreadyIncluded = 2002 'unused in Roslyn.
'ERR_DuplicateResponseFile = 2003 unused in Roslyn.
'ERR_NoMemory = 2004
ERR_ArgumentRequired = 2006
WRN_BadSwitch = 2007
ERR_NoSources = 2008
ERR_SwitchNeedsBool = 2009
'ERR_CompileFailed = 2010 unused in Roslyn.
ERR_NoResponseFile = 2011
ERR_CantOpenFileWrite = 2012
ERR_InvalidSwitchValue = 2014
ERR_BinaryFile = 2015
ERR_BadCodepage = 2016
ERR_LibNotFound = 2017
'ERR_MaximumErrors = 2020 unused in Roslyn.
ERR_IconFileAndWin32ResFile = 2023
'WRN_ReservedReference = 2024 ' unused by native compiler due to bug.
WRN_NoConfigInResponseFile = 2025
' WRN_InvalidWarningId = 2026 ' unused in Roslyn.
'ERR_WatsonSendNotOptedIn = 2027
' WRN_SwitchNoBool = 2028 'unused in Roslyn
ERR_NoSourcesOut = 2029
ERR_NeedModule = 2030
ERR_InvalidAssemblyName = 2031
FTL_InvalidInputFileName = 2032 ' new in Roslyn
ERR_ConflictingManifestSwitches = 2033
WRN_IgnoreModuleManifest = 2034
'ERR_NoDefaultManifest = 2035
'ERR_InvalidSwitchValue1 = 2036
WRN_BadUILang = 2038 ' new in Roslyn
ERR_VBCoreNetModuleConflict = 2042
ERR_InvalidFormatForGuidForOption = 2043
ERR_MissingGuidForOption = 2044
ERR_BadChecksumAlgorithm = 2045
ERR_MutuallyExclusiveOptions = 2046
ERR_BadSwitchValue = 2047
'// The naming convention is that if your error requires arguments, to append
'// the number of args taken, e.g. AmbiguousName2
'//
ERR_InvalidInNamespace = 30001
ERR_UndefinedType1 = 30002
ERR_MissingNext = 30003
ERR_IllegalCharConstant = 30004
'//If you make any change involving these errors, such as creating more specific versions for use
'//in other contexts, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
ERR_UnreferencedAssemblyEvent3 = 30005
ERR_UnreferencedModuleEvent3 = 30006
' ERR_UnreferencedAssemblyBase3 = 30007
' ERR_UnreferencedModuleBase3 = 30008 - This has been superceded by ERR_UnreferencedModuleEvent3
' ERR_UnreferencedAssemblyImplements3 = 30009
'ERR_UnreferencedModuleImplements3 = 30010 - This has been superceded by ERR_UnreferencedModuleEvent3
'ERR_CodegenError = 30011
ERR_LbExpectedEndIf = 30012
ERR_LbNoMatchingIf = 30013
ERR_LbBadElseif = 30014
ERR_InheritsFromRestrictedType1 = 30015
ERR_InvOutsideProc = 30016
ERR_DelegateCantImplement = 30018
ERR_DelegateCantHandleEvents = 30019
ERR_IsOperatorRequiresReferenceTypes1 = 30020
ERR_TypeOfRequiresReferenceType1 = 30021
ERR_ReadOnlyHasSet = 30022
ERR_WriteOnlyHasGet = 30023
ERR_InvInsideProc = 30024
ERR_EndProp = 30025
ERR_EndSubExpected = 30026
ERR_EndFunctionExpected = 30027
ERR_LbElseNoMatchingIf = 30028
ERR_CantRaiseBaseEvent = 30029
ERR_TryWithoutCatchOrFinally = 30030
' ERR_FullyQualifiedNameTooLong1 = 30031 ' Deprecated in favor of ERR_TooLongMetadataName
ERR_EventsCantBeFunctions = 30032
' ERR_IdTooLong = 30033 ' Deprecated in favor of ERR_TooLongMetadataName
ERR_MissingEndBrack = 30034
ERR_Syntax = 30035
ERR_Overflow = 30036
ERR_IllegalChar = 30037
ERR_StrictDisallowsObjectOperand1 = 30038
ERR_LoopControlMustNotBeProperty = 30039
ERR_MethodBodyNotAtLineStart = 30040
ERR_MaximumNumberOfErrors = 30041
ERR_UseOfKeywordNotInInstanceMethod1 = 30043
ERR_UseOfKeywordFromStructure1 = 30044
ERR_BadAttributeConstructor1 = 30045
ERR_ParamArrayWithOptArgs = 30046
ERR_ExpectedArray1 = 30049
ERR_ParamArrayNotArray = 30050
ERR_ParamArrayRank = 30051
ERR_ArrayRankLimit = 30052
ERR_AsNewArray = 30053
ERR_TooManyArgs1 = 30057
ERR_ExpectedCase = 30058
ERR_RequiredConstExpr = 30059
ERR_RequiredConstConversion2 = 30060
ERR_InvalidMe = 30062
ERR_ReadOnlyAssignment = 30064
ERR_ExitSubOfFunc = 30065
ERR_ExitPropNot = 30066
ERR_ExitFuncOfSub = 30067
ERR_LValueRequired = 30068
ERR_ForIndexInUse1 = 30069
ERR_NextForMismatch1 = 30070
ERR_CaseElseNoSelect = 30071
ERR_CaseNoSelect = 30072
ERR_CantAssignToConst = 30074
ERR_NamedSubscript = 30075
ERR_ExpectedEndIf = 30081
ERR_ExpectedEndWhile = 30082
ERR_ExpectedLoop = 30083
ERR_ExpectedNext = 30084
ERR_ExpectedEndWith = 30085
ERR_ElseNoMatchingIf = 30086
ERR_EndIfNoMatchingIf = 30087
ERR_EndSelectNoSelect = 30088
ERR_ExitDoNotWithinDo = 30089
ERR_EndWhileNoWhile = 30090
ERR_LoopNoMatchingDo = 30091
ERR_NextNoMatchingFor = 30092
ERR_EndWithWithoutWith = 30093
ERR_MultiplyDefined1 = 30094
ERR_ExpectedEndSelect = 30095
ERR_ExitForNotWithinFor = 30096
ERR_ExitWhileNotWithinWhile = 30097
ERR_ReadOnlyProperty1 = 30098
ERR_ExitSelectNotWithinSelect = 30099
ERR_BranchOutOfFinally = 30101
ERR_QualNotObjectRecord1 = 30103
ERR_TooFewIndices = 30105
ERR_TooManyIndices = 30106
ERR_EnumNotExpression1 = 30107
ERR_TypeNotExpression1 = 30108
ERR_ClassNotExpression1 = 30109
ERR_StructureNotExpression1 = 30110
ERR_InterfaceNotExpression1 = 30111
ERR_NamespaceNotExpression1 = 30112
ERR_BadNamespaceName1 = 30113
ERR_XmlPrefixNotExpression = 30114
ERR_MultipleExtends = 30121
'ERR_NoStopInDebugger = 30122
'ERR_NoEndInDebugger = 30123
ERR_PropMustHaveGetSet = 30124
ERR_WriteOnlyHasNoWrite = 30125
ERR_ReadOnlyHasNoGet = 30126
ERR_BadAttribute1 = 30127
' ERR_BadSecurityAttribute1 = 30128 ' we're now reporting more detailed diagnostics: ERR_SecurityAttributeMissingAction or ERR_SecurityAttributeInvalidAction
'ERR_BadAssemblyAttribute1 = 30129
'ERR_BadModuleAttribute1 = 30130
' ERR_ModuleSecurityAttributeNotAllowed1 = 30131 ' We now report ERR_SecurityAttributeInvalidTarget instead.
ERR_LabelNotDefined1 = 30132
'ERR_NoGotosInDebugger = 30133
'ERR_NoLabelsInDebugger = 30134
'ERR_NoSyncLocksInDebugger = 30135
ERR_ErrorCreatingWin32ResourceFile = 30136
'ERR_ErrorSavingWin32ResourceFile = 30137 abandoned. no longer "saving" a temporary resource file.
ERR_UnableToCreateTempFile = 30138 'changed from ERR_UnableToCreateTempFileInPath1. now takes only one argument
'ERR_ErrorSettingManifestOption = 30139
'ERR_ErrorCreatingManifest = 30140
'ERR_UnableToCreateALinkAPI = 30141
'ERR_UnableToGenerateRefToMetaDataFile1 = 30142
'ERR_UnableToEmbedResourceFile1 = 30143 ' We now report ERR_UnableToOpenResourceFile1 instead.
'ERR_UnableToLinkResourceFile1 = 30144 ' We now report ERR_UnableToOpenResourceFile1 instead.
'ERR_UnableToEmitAssembly = 30145
'ERR_UnableToSignAssembly = 30146
'ERR_NoReturnsInDebugger = 30147
ERR_RequiredNewCall2 = 30148
ERR_UnimplementedMember3 = 30149
' ERR_UnimplementedProperty3 = 30154
ERR_BadWithRef = 30157
' ERR_ExpectedNewableClass1 = 30166 unused in Roslyn. We now report nothing
' ERR_TypeConflict7 = 30175 unused in Roslyn. We now report BC30179
ERR_DuplicateAccessCategoryUsed = 30176
ERR_DuplicateModifierCategoryUsed = 30177
ERR_DuplicateSpecifier = 30178
ERR_TypeConflict6 = 30179
ERR_UnrecognizedTypeKeyword = 30180
ERR_ExtraSpecifiers = 30181
ERR_UnrecognizedType = 30182
ERR_InvalidUseOfKeyword = 30183
ERR_InvalidEndEnum = 30184
ERR_MissingEndEnum = 30185
'ERR_NoUsingInDebugger = 30186
ERR_ExpectedDeclaration = 30188
ERR_ParamArrayMustBeLast = 30192
ERR_SpecifiersInvalidOnInheritsImplOpt = 30193
ERR_ExpectedSpecifier = 30195
ERR_ExpectedComma = 30196
ERR_ExpectedAs = 30197
ERR_ExpectedRparen = 30198
ERR_ExpectedLparen = 30199
ERR_InvalidNewInType = 30200
ERR_ExpectedExpression = 30201
ERR_ExpectedOptional = 30202
ERR_ExpectedIdentifier = 30203
ERR_ExpectedIntLiteral = 30204
ERR_ExpectedEOS = 30205
ERR_ExpectedForOptionStmt = 30206
ERR_InvalidOptionCompare = 30207
ERR_ExpectedOptionCompare = 30208
ERR_StrictDisallowImplicitObject = 30209
ERR_StrictDisallowsImplicitProc = 30210
ERR_StrictDisallowsImplicitArgs = 30211
ERR_InvalidParameterSyntax = 30213
ERR_ExpectedSubFunction = 30215
ERR_ExpectedStringLiteral = 30217
ERR_MissingLibInDeclare = 30218
ERR_DelegateNoInvoke1 = 30220
ERR_MissingIsInTypeOf = 30224
ERR_DuplicateOption1 = 30225
ERR_ModuleCantInherit = 30230
ERR_ModuleCantImplement = 30231
ERR_BadImplementsType = 30232
ERR_BadConstFlags1 = 30233
ERR_BadWithEventsFlags1 = 30234
ERR_BadDimFlags1 = 30235
ERR_DuplicateParamName1 = 30237
ERR_LoopDoubleCondition = 30238
ERR_ExpectedRelational = 30239
ERR_ExpectedExitKind = 30240
ERR_ExpectedNamedArgument = 30241
ERR_BadMethodFlags1 = 30242
ERR_BadEventFlags1 = 30243
ERR_BadDeclareFlags1 = 30244
ERR_BadLocalConstFlags1 = 30246
ERR_BadLocalDimFlags1 = 30247
ERR_ExpectedConditionalDirective = 30248
ERR_ExpectedEQ = 30249
ERR_ConstructorNotFound1 = 30251
ERR_InvalidEndInterface = 30252
ERR_MissingEndInterface = 30253
ERR_InheritsFrom2 = 30256
ERR_InheritanceCycle1 = 30257
ERR_InheritsFromNonClass = 30258
ERR_MultiplyDefinedType3 = 30260
ERR_BadOverrideAccess2 = 30266
ERR_CantOverrideNotOverridable2 = 30267
ERR_DuplicateProcDef1 = 30269
ERR_BadInterfaceMethodFlags1 = 30270
ERR_NamedParamNotFound2 = 30272
ERR_BadInterfacePropertyFlags1 = 30273
ERR_NamedArgUsedTwice2 = 30274
ERR_InterfaceCantUseEventSpecifier1 = 30275
ERR_TypecharNoMatch2 = 30277
ERR_ExpectedSubOrFunction = 30278
ERR_BadEmptyEnum1 = 30280
ERR_InvalidConstructorCall = 30282
ERR_CantOverrideConstructor = 30283
ERR_OverrideNotNeeded3 = 30284
ERR_ExpectedDot = 30287
ERR_DuplicateLocals1 = 30288
ERR_InvInsideEndsProc = 30289
ERR_LocalSameAsFunc = 30290
ERR_RecordEmbeds2 = 30293
ERR_RecordCycle2 = 30294
ERR_InterfaceCycle1 = 30296
ERR_SubNewCycle2 = 30297
ERR_SubNewCycle1 = 30298
ERR_InheritsFromCantInherit3 = 30299
ERR_OverloadWithOptional2 = 30300
ERR_OverloadWithReturnType2 = 30301
ERR_TypeCharWithType1 = 30302
ERR_TypeCharOnSub = 30303
ERR_OverloadWithDefault2 = 30305
ERR_MissingSubscript = 30306
ERR_OverrideWithDefault2 = 30307
ERR_OverrideWithOptional2 = 30308
ERR_FieldOfValueFieldOfMarshalByRef3 = 30310
ERR_TypeMismatch2 = 30311
ERR_CaseAfterCaseElse = 30321
ERR_ConvertArrayMismatch4 = 30332
ERR_ConvertObjectArrayMismatch3 = 30333
ERR_ForLoopType1 = 30337
ERR_OverloadWithByref2 = 30345
ERR_InheritsFromNonInterface = 30354
ERR_BadInterfaceOrderOnInherits = 30357
ERR_DuplicateDefaultProps1 = 30359
ERR_DefaultMissingFromProperty2 = 30361
ERR_OverridingPropertyKind2 = 30362
ERR_NewInInterface = 30363
ERR_BadFlagsOnNew1 = 30364
ERR_OverloadingPropertyKind2 = 30366
ERR_NoDefaultNotExtend1 = 30367
ERR_OverloadWithArrayVsParamArray2 = 30368
ERR_BadInstanceMemberAccess = 30369
ERR_ExpectedRbrace = 30370
ERR_ModuleAsType1 = 30371
ERR_NewIfNullOnNonClass = 30375
'ERR_NewIfNullOnAbstractClass1 = 30376
ERR_CatchAfterFinally = 30379
ERR_CatchNoMatchingTry = 30380
ERR_FinallyAfterFinally = 30381
ERR_FinallyNoMatchingTry = 30382
ERR_EndTryNoTry = 30383
ERR_ExpectedEndTry = 30384
ERR_BadDelegateFlags1 = 30385
ERR_NoConstructorOnBase2 = 30387
ERR_InaccessibleSymbol2 = 30389
ERR_InaccessibleMember3 = 30390
ERR_CatchNotException1 = 30392
ERR_ExitTryNotWithinTry = 30393
ERR_BadRecordFlags1 = 30395
ERR_BadEnumFlags1 = 30396
ERR_BadInterfaceFlags1 = 30397
ERR_OverrideWithByref2 = 30398
ERR_MyBaseAbstractCall1 = 30399
ERR_IdentNotMemberOfInterface4 = 30401
ERR_ImplementingInterfaceWithDifferentTupleNames5 = 30402
'//We intentionally use argument '3' for the delegate name. This makes generating overload resolution errors
'//easy. To make it more clear that were doing this, we name the message DelegateBindingMismatch3_2.
'//This differentiates its from DelegateBindingMismatch3_3, which actually takes 3 parameters instead of 2.
'//This is a workaround, but it makes the logic for reporting overload resolution errors easier error report more straight forward.
'ERR_DelegateBindingMismatch3_2 = 30408
ERR_WithEventsRequiresClass = 30412
ERR_WithEventsAsStruct = 30413
ERR_ConvertArrayRankMismatch2 = 30414
ERR_RedimRankMismatch = 30415
ERR_StartupCodeNotFound1 = 30420
ERR_ConstAsNonConstant = 30424
ERR_InvalidEndSub = 30429
ERR_InvalidEndFunction = 30430
ERR_InvalidEndProperty = 30431
ERR_ModuleCantUseMethodSpecifier1 = 30433
ERR_ModuleCantUseEventSpecifier1 = 30434
ERR_StructCantUseVarSpecifier1 = 30435
'ERR_ModuleCantUseMemberSpecifier1 = 30436 Now reporting BC30735
ERR_InvalidOverrideDueToReturn2 = 30437
ERR_ConstantWithNoValue = 30438
ERR_ExpressionOverflow1 = 30439
'ERR_ExpectedEndTryCatch = 30441 - No Longer Reported. Removed per bug 926779
'ERR_ExpectedEndTryFinally = 30442 - No Longer Reported. Removed per bug 926779
ERR_DuplicatePropertyGet = 30443
ERR_DuplicatePropertySet = 30444
' ERR_ConstAggregate = 30445 Now giving BC30424
ERR_NameNotDeclared1 = 30451
ERR_BinaryOperands3 = 30452
ERR_ExpectedProcedure = 30454
ERR_OmittedArgument2 = 30455
ERR_NameNotMember2 = 30456
'ERR_NoTypeNamesAvailable = 30458
ERR_EndClassNoClass = 30460
ERR_BadClassFlags1 = 30461
ERR_ImportsMustBeFirst = 30465
ERR_NonNamespaceOrClassOnImport2 = 30467
ERR_TypecharNotallowed = 30468
ERR_ObjectReferenceNotSupplied = 30469
ERR_MyClassNotInClass = 30470
ERR_IndexedNotArrayOrProc = 30471
ERR_EventSourceIsArray = 30476
ERR_SharedConstructorWithParams = 30479
ERR_SharedConstructorIllegalSpec1 = 30480
ERR_ExpectedEndClass = 30481
ERR_UnaryOperand2 = 30487
ERR_BadFlagsWithDefault1 = 30490
ERR_VoidValue = 30491
ERR_ConstructorFunction = 30493
'ERR_LineTooLong = 30494 - No longer reported. Removed per 926916
ERR_InvalidLiteralExponent = 30495
ERR_NewCannotHandleEvents = 30497
ERR_CircularEvaluation1 = 30500
ERR_BadFlagsOnSharedMeth1 = 30501
ERR_BadFlagsOnSharedProperty1 = 30502
ERR_BadFlagsOnStdModuleProperty1 = 30503
ERR_SharedOnProcThatImpl = 30505
ERR_NoWithEventsVarOnHandlesList = 30506
ERR_AccessMismatch6 = 30508
ERR_InheritanceAccessMismatch5 = 30509
ERR_NarrowingConversionDisallowed2 = 30512
ERR_NoArgumentCountOverloadCandidates1 = 30516
ERR_NoViableOverloadCandidates1 = 30517
ERR_NoCallableOverloadCandidates2 = 30518
ERR_NoNonNarrowingOverloadCandidates2 = 30519
ERR_ArgumentNarrowing3 = 30520
ERR_NoMostSpecificOverload2 = 30521
ERR_NotMostSpecificOverload = 30522
ERR_OverloadCandidate2 = 30523
ERR_NoGetProperty1 = 30524
ERR_NoSetProperty1 = 30526
'ERR_ArrayType2 = 30528
ERR_ParamTypingInconsistency = 30529
ERR_ParamNameFunctionNameCollision = 30530
ERR_DateToDoubleConversion = 30532
ERR_DoubleToDateConversion = 30533
ERR_ZeroDivide = 30542
ERR_TryAndOnErrorDoNotMix = 30544
ERR_PropertyAccessIgnored = 30545
ERR_InterfaceNoDefault1 = 30547
ERR_InvalidAssemblyAttribute1 = 30548
ERR_InvalidModuleAttribute1 = 30549
ERR_AmbiguousInUnnamedNamespace1 = 30554
ERR_DefaultMemberNotProperty1 = 30555
ERR_AmbiguousInNamespace2 = 30560
ERR_AmbiguousInImports2 = 30561
ERR_AmbiguousInModules2 = 30562
' ERR_AmbiguousInApplicationObject2 = 30563 ' comment out in Dev10
ERR_ArrayInitializerTooFewDimensions = 30565
ERR_ArrayInitializerTooManyDimensions = 30566
ERR_InitializerTooFewElements1 = 30567
ERR_InitializerTooManyElements1 = 30568
ERR_NewOnAbstractClass = 30569
ERR_DuplicateNamedImportAlias1 = 30572
ERR_DuplicatePrefix = 30573
ERR_StrictDisallowsLateBinding = 30574
' ERR_PropertyMemberSyntax = 30576 unused in Roslyn
ERR_AddressOfOperandNotMethod = 30577
ERR_EndExternalSource = 30578
ERR_ExpectedEndExternalSource = 30579
ERR_NestedExternalSource = 30580
ERR_AddressOfNotDelegate1 = 30581
ERR_SyncLockRequiresReferenceType1 = 30582
ERR_MethodAlreadyImplemented2 = 30583
ERR_DuplicateInInherits1 = 30584
ERR_NamedParamArrayArgument = 30587
ERR_OmittedParamArrayArgument = 30588
ERR_ParamArrayArgumentMismatch = 30589
ERR_EventNotFound1 = 30590
'ERR_NoDefaultSource = 30591
ERR_ModuleCantUseVariableSpecifier1 = 30593
ERR_SharedEventNeedsSharedHandler = 30594
ERR_ExpectedMinus = 30601
ERR_InterfaceMemberSyntax = 30602
ERR_InvInsideInterface = 30603
ERR_InvInsideEndsInterface = 30604
ERR_BadFlagsInNotInheritableClass1 = 30607
ERR_UnimplementedMustOverride = 30609 ' substituted into ERR_BaseOnlyClassesMustBeExplicit2
ERR_BaseOnlyClassesMustBeExplicit2 = 30610
ERR_NegativeArraySize = 30611
ERR_MyClassAbstractCall1 = 30614
ERR_EndDisallowedInDllProjects = 30615
ERR_BlockLocalShadowing1 = 30616
ERR_ModuleNotAtNamespace = 30617
ERR_NamespaceNotAtNamespace = 30618
ERR_InvInsideEndsEnum = 30619
ERR_InvalidOptionStrict = 30620
ERR_EndStructureNoStructure = 30621
ERR_EndModuleNoModule = 30622
ERR_EndNamespaceNoNamespace = 30623
ERR_ExpectedEndStructure = 30624
ERR_ExpectedEndModule = 30625
ERR_ExpectedEndNamespace = 30626
ERR_OptionStmtWrongOrder = 30627
ERR_StructCantInherit = 30628
ERR_NewInStruct = 30629
ERR_InvalidEndGet = 30630
ERR_MissingEndGet = 30631
ERR_InvalidEndSet = 30632
ERR_MissingEndSet = 30633
ERR_InvInsideEndsProperty = 30634
ERR_DuplicateWriteabilityCategoryUsed = 30635
ERR_ExpectedGreater = 30636
ERR_AttributeStmtWrongOrder = 30637
ERR_NoExplicitArraySizes = 30638
ERR_BadPropertyFlags1 = 30639
ERR_InvalidOptionExplicit = 30640
ERR_MultipleParameterSpecifiers = 30641
ERR_MultipleOptionalParameterSpecifiers = 30642
ERR_UnsupportedProperty1 = 30643
ERR_InvalidOptionalParameterUsage1 = 30645
ERR_ReturnFromNonFunction = 30647
ERR_UnterminatedStringLiteral = 30648
ERR_UnsupportedType1 = 30649
ERR_InvalidEnumBase = 30650
ERR_ByRefIllegal1 = 30651
'//If you make any change involving these errors, such as creating more specific versions for use
'//in other contexts, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
ERR_UnreferencedAssembly3 = 30652
ERR_UnreferencedModule3 = 30653
ERR_ReturnWithoutValue = 30654
' ERR_CantLoadStdLibrary1 = 30655 roslyn doesn't use special messages when well-known assemblies cannot be loaded.
ERR_UnsupportedField1 = 30656
ERR_UnsupportedMethod1 = 30657
ERR_NoNonIndexProperty1 = 30658
ERR_BadAttributePropertyType1 = 30659
ERR_LocalsCannotHaveAttributes = 30660
ERR_PropertyOrFieldNotDefined1 = 30661
ERR_InvalidAttributeUsage2 = 30662
ERR_InvalidMultipleAttributeUsage1 = 30663
ERR_CantThrowNonException = 30665
ERR_MustBeInCatchToRethrow = 30666
ERR_ParamArrayMustBeByVal = 30667
ERR_UseOfObsoleteSymbol2 = 30668
ERR_RedimNoSizes = 30670
ERR_InitWithMultipleDeclarators = 30671
ERR_InitWithExplicitArraySizes = 30672
ERR_EndSyncLockNoSyncLock = 30674
ERR_ExpectedEndSyncLock = 30675
ERR_NameNotEvent2 = 30676
ERR_AddOrRemoveHandlerEvent = 30677
ERR_UnrecognizedEnd = 30678
ERR_ArrayInitForNonArray2 = 30679
ERR_EndRegionNoRegion = 30680
ERR_ExpectedEndRegion = 30681
ERR_InheritsStmtWrongOrder = 30683
ERR_AmbiguousAcrossInterfaces3 = 30685
ERR_DefaultPropertyAmbiguousAcrossInterfaces4 = 30686
ERR_InterfaceEventCantUse1 = 30688
ERR_ExecutableAsDeclaration = 30689
ERR_StructureNoDefault1 = 30690
' ERR_TypeMemberAsExpression2 = 30691 Now giving BC30109
ERR_MustShadow2 = 30695
'ERR_OverloadWithOptionalTypes2 = 30696
ERR_OverrideWithOptionalTypes2 = 30697
'ERR_UnableToGetTempPath = 30698
'ERR_NameNotDeclaredDebug1 = 30699
'// This error should never be seen.
'ERR_NoSideEffects = 30700
'ERR_InvalidNothing = 30701
'ERR_IndexOutOfRange1 = 30702
'ERR_RuntimeException2 = 30703
'ERR_RuntimeException = 30704
'ERR_ObjectReferenceIsNothing1 = 30705
'// This error should never be seen.
'ERR_ExpressionNotValidInEE = 30706
'ERR_UnableToEvaluateExpression = 30707
'ERR_UnableToEvaluateLoops = 30708
'ERR_NoDimsInDebugger = 30709
ERR_ExpectedEndOfExpression = 30710
'ERR_SetValueNotAllowedOnNonLeafFrame = 30711
'ERR_UnableToClassInformation1 = 30712
'ERR_NoExitInDebugger = 30713
'ERR_NoResumeInDebugger = 30714
'ERR_NoCatchInDebugger = 30715
'ERR_NoFinallyInDebugger = 30716
'ERR_NoTryInDebugger = 30717
'ERR_NoSelectInDebugger = 30718
'ERR_NoCaseInDebugger = 30719
'ERR_NoOnErrorInDebugger = 30720
'ERR_EvaluationAborted = 30721
'ERR_EvaluationTimeout = 30722
'ERR_EvaluationNoReturnValue = 30723
'ERR_NoErrorStatementInDebugger = 30724
'ERR_NoThrowStatementInDebugger = 30725
'ERR_NoWithContextInDebugger = 30726
ERR_StructsCannotHandleEvents = 30728
ERR_OverridesImpliesOverridable = 30730
'ERR_NoAddressOfInDebugger = 30731
'ERR_EvaluationOfWebMethods = 30732
ERR_LocalNamedSameAsParam1 = 30734
ERR_ModuleCantUseTypeSpecifier1 = 30735
'ERR_EvaluationBadStartPoint = 30736
ERR_InValidSubMainsFound1 = 30737
ERR_MoreThanOneValidMainWasFound2 = 30738
'ERR_NoRaiseEventOfInDebugger = 30739
'ERR_InvalidCast2 = 30741
ERR_CannotConvertValue2 = 30742
'ERR_ArrayElementIsNothing = 30744
'ERR_InternalCompilerError = 30747
'ERR_InvalidCast1 = 30748
'ERR_UnableToGetValue = 30749
'ERR_UnableToLoadType1 = 30750
'ERR_UnableToGetTypeInformationFor1 = 30751
ERR_OnErrorInSyncLock = 30752
ERR_NarrowingConversionCollection2 = 30753
ERR_GotoIntoTryHandler = 30754
ERR_GotoIntoSyncLock = 30755
ERR_GotoIntoWith = 30756
ERR_GotoIntoFor = 30757
ERR_BadAttributeNonPublicConstructor = 30758
'ERR_ArrayElementIsNothing1 = 30759
'ERR_ObjectReferenceIsNothing = 30760
' ERR_StarliteDisallowsLateBinding = 30762
' ERR_StarliteBadDeclareFlags = 30763
' ERR_NoStarliteOverloadResolution = 30764
'ERR_NoSupportFileIOKeywords1 = 30766
' ERR_NoSupportGetStatement = 30767 - starlite error message
' ERR_NoSupportLineKeyword = 30768 cut from Roslyn
' ERR_StarliteDisallowsEndStatement = 30769 cut from Roslyn
ERR_DefaultEventNotFound1 = 30770
ERR_InvalidNonSerializedUsage = 30772
'ERR_NoContinueInDebugger = 30780
ERR_ExpectedContinueKind = 30781
ERR_ContinueDoNotWithinDo = 30782
ERR_ContinueForNotWithinFor = 30783
ERR_ContinueWhileNotWithinWhile = 30784
ERR_DuplicateParameterSpecifier = 30785
ERR_ModuleCantUseDLLDeclareSpecifier1 = 30786
ERR_StructCantUseDLLDeclareSpecifier1 = 30791
ERR_TryCastOfValueType1 = 30792
ERR_TryCastOfUnconstrainedTypeParam1 = 30793
ERR_AmbiguousDelegateBinding2 = 30794
ERR_SharedStructMemberCannotSpecifyNew = 30795
ERR_GenericSubMainsFound1 = 30796
ERR_GeneralProjectImportsError3 = 30797
ERR_InvalidTypeForAliasesImport2 = 30798
ERR_UnsupportedConstant2 = 30799
ERR_ObsoleteArgumentsNeedParens = 30800
ERR_ObsoleteLineNumbersAreLabels = 30801
ERR_ObsoleteStructureNotType = 30802
'ERR_ObsoleteDecimalNotCurrency = 30803 cut from Roslyn
ERR_ObsoleteObjectNotVariant = 30804
'ERR_ObsoleteArrayBounds = 30805 unused in Roslyn
ERR_ObsoleteLetSetNotNeeded = 30807
ERR_ObsoletePropertyGetLetSet = 30808
ERR_ObsoleteWhileWend = 30809
'ERR_ObsoleteStaticMethod = 30810 cut from Roslyn
ERR_ObsoleteRedimAs = 30811
ERR_ObsoleteOptionalWithoutValue = 30812
ERR_ObsoleteGosub = 30814
'ERR_ObsoleteFileIOKeywords1 = 30815 cut from Roslyn
'ERR_ObsoleteDebugKeyword1 = 30816 cut from Roslyn
ERR_ObsoleteOnGotoGosub = 30817
'ERR_ObsoleteMathCompatKeywords1 = 30818 cut from Roslyn
'ERR_ObsoleteMathKeywords2 = 30819 cut from Roslyn
'ERR_ObsoleteLsetKeyword1 = 30820 cut from Roslyn
'ERR_ObsoleteRsetKeyword1 = 30821 cut from Roslyn
'ERR_ObsoleteNullKeyword1 = 30822 cut from Roslyn
'ERR_ObsoleteEmptyKeyword1 = 30823 cut from Roslyn
ERR_ObsoleteEndIf = 30826
ERR_ObsoleteExponent = 30827
ERR_ObsoleteAsAny = 30828
ERR_ObsoleteGetStatement = 30829
'ERR_ObsoleteLineKeyword = 30830 cut from Roslyn
ERR_OverrideWithArrayVsParamArray2 = 30906
'// CONSIDER :harishk - improve this error message
ERR_CircularBaseDependencies4 = 30907
ERR_NestedBase2 = 30908
ERR_AccessMismatchOutsideAssembly4 = 30909
ERR_InheritanceAccessMismatchOutside3 = 30910
ERR_UseOfObsoletePropertyAccessor3 = 30911
ERR_UseOfObsoletePropertyAccessor2 = 30912
ERR_AccessMismatchImplementedEvent6 = 30914
ERR_AccessMismatchImplementedEvent4 = 30915
ERR_InheritanceCycleInImportedType1 = 30916
ERR_NoNonObsoleteConstructorOnBase3 = 30917
ERR_NoNonObsoleteConstructorOnBase4 = 30918
ERR_RequiredNonObsoleteNewCall3 = 30919
ERR_RequiredNonObsoleteNewCall4 = 30920
ERR_InheritsTypeArgAccessMismatch7 = 30921
ERR_InheritsTypeArgAccessMismatchOutside5 = 30922
'ERR_AccessMismatchTypeArgImplEvent7 = 30923 unused in Roslyn
'ERR_AccessMismatchTypeArgImplEvent5 = 30924 unused in Roslyn
ERR_PartialTypeAccessMismatch3 = 30925
ERR_PartialTypeBadMustInherit1 = 30926
ERR_MustOverOnNotInheritPartClsMem1 = 30927
ERR_BaseMismatchForPartialClass3 = 30928
ERR_PartialTypeTypeParamNameMismatch3 = 30931
ERR_PartialTypeConstraintMismatch1 = 30932
ERR_LateBoundOverloadInterfaceCall1 = 30933
ERR_RequiredAttributeConstConversion2 = 30934
ERR_AmbiguousOverrides3 = 30935
ERR_OverriddenCandidate1 = 30936
ERR_AmbiguousImplements3 = 30937
ERR_AddressOfNotCreatableDelegate1 = 30939
'ERR_ReturnFromEventMethod = 30940 unused in Roslyn
'ERR_BadEmptyStructWithCustomEvent1 = 30941
ERR_ComClassGenericMethod = 30943
ERR_SyntaxInCastOp = 30944
'ERR_UnimplementedBadMemberEvent = 30945 Cut in Roslyn
'ERR_EvaluationStopRequested = 30946
'ERR_EvaluationSuspendRequested = 30947
'ERR_EvaluationUnscheduledFiber = 30948
ERR_ArrayInitializerForNonConstDim = 30949
ERR_DelegateBindingFailure3 = 30950
'ERR_DelegateBindingTypeInferenceFails2 = 30952
'ERR_ConstraintViolationError1 = 30953
'ERR_ConstraintsFailedForInferredArgs2 = 30954
'ERR_TypeMismatchDLLProjectMix6 = 30955
'ERR_EvaluationPriorTimeout = 30957
'ERR_EvaluationENCObjectOutdated = 30958
' Obsolete ERR_TypeRefFromMetadataToVBUndef = 30960
'ERR_TypeMismatchMixedDLLs6 = 30961
'ERR_ReferencedAssemblyCausesCycle3 = 30962
'ERR_AssemblyRefAssembly2 = 30963
'ERR_AssemblyRefProject2 = 30964
'ERR_ProjectRefAssembly2 = 30965
'ERR_ProjectRefProject2 = 30966
'ERR_ReferencedAssembliesAmbiguous4 = 30967
'ERR_ReferencedAssembliesAmbiguous6 = 30968
'ERR_ReferencedProjectsAmbiguous4 = 30969
'ERR_GeneralErrorMixedDLLs5 = 30970
'ERR_GeneralErrorDLLProjectMix5 = 30971
ERR_StructLayoutAttributeNotAllowed = 30972
'ERR_ClassNotLoadedDuringDebugging = 30973
'ERR_UnableToEvaluateComment = 30974
'ERR_ForIndexInUse = 30975
'ERR_NextForMismatch = 30976
ERR_IterationVariableShadowLocal1 = 30978
ERR_InvalidOptionInfer = 30979
ERR_CircularInference1 = 30980
ERR_InAccessibleOverridingMethod5 = 30981
ERR_NoSuitableWidestType1 = 30982
ERR_AmbiguousWidestType3 = 30983
ERR_ExpectedAssignmentOperatorInInit = 30984
ERR_ExpectedQualifiedNameInInit = 30985
ERR_ExpectedLbrace = 30987
ERR_UnrecognizedTypeOrWith = 30988
ERR_DuplicateAggrMemberInit1 = 30989
ERR_NonFieldPropertyAggrMemberInit1 = 30990
ERR_SharedMemberAggrMemberInit1 = 30991
ERR_ParameterizedPropertyInAggrInit1 = 30992
ERR_NoZeroCountArgumentInitCandidates1 = 30993
ERR_AggrInitInvalidForObject = 30994
'ERR_BadWithRefInConstExpr = 30995
ERR_InitializerExpected = 30996
ERR_LineContWithCommentOrNoPrecSpace = 30999
' ERR_MemberNotFoundForNoPia = 31000 not used in Roslyn. This looks to be a VB EE message
ERR_InvInsideEnum = 31001
ERR_InvInsideBlock = 31002
ERR_UnexpectedExpressionStatement = 31003
ERR_WinRTEventWithoutDelegate = 31004
ERR_SecurityCriticalAsyncInClassOrStruct = 31005
ERR_SecurityCriticalAsync = 31006
ERR_BadModuleFile1 = 31007
ERR_BadRefLib1 = 31011
'ERR_UnableToLoadDll1 = 31013
'ERR_BadDllEntrypoint2 = 31014
'ERR_BadOutputFile1 = 31019
'ERR_BadOutputStream = 31020
'ERR_DeadBackgroundThread = 31021
'ERR_XMLParserError = 31023
'ERR_UnableToCreateMetaDataAPI = 31024
'ERR_UnableToOpenFile1 = 31027
ERR_EventHandlerSignatureIncompatible2 = 31029
ERR_ConditionalCompilationConstantNotValid = 31030
'ERR_ProjectCCError0 = 31031
ERR_InterfaceImplementedTwice1 = 31033
ERR_InterfaceNotImplemented1 = 31035
ERR_AmbiguousImplementsMember3 = 31040
'ERR_BadInterfaceMember = 31041
ERR_ImplementsOnNew = 31042
ERR_ArrayInitInStruct = 31043
ERR_EventTypeNotDelegate = 31044
ERR_ProtectedTypeOutsideClass = 31047
ERR_DefaultPropertyWithNoParams = 31048
ERR_InitializerInStruct = 31049
ERR_DuplicateImport1 = 31051
ERR_BadModuleFlags1 = 31052
ERR_ImplementsStmtWrongOrder = 31053
ERR_MemberConflictWithSynth4 = 31058
ERR_SynthMemberClashesWithSynth7 = 31059
ERR_SynthMemberClashesWithMember5 = 31060
ERR_MemberClashesWithSynth6 = 31061
ERR_SetHasOnlyOneParam = 31063
ERR_SetValueNotPropertyType = 31064
ERR_SetHasToBeByVal1 = 31065
ERR_StructureCantUseProtected = 31067
ERR_BadInterfaceDelegateSpecifier1 = 31068
ERR_BadInterfaceEnumSpecifier1 = 31069
ERR_BadInterfaceClassSpecifier1 = 31070
ERR_BadInterfaceStructSpecifier1 = 31071
'ERR_WarningTreatedAsError = 31072
'ERR_DelegateConstructorMissing1 = 31074 unused in Roslyn
ERR_UseOfObsoleteSymbolNoMessage1 = 31075
ERR_MetaDataIsNotAssembly = 31076
ERR_MetaDataIsNotModule = 31077
ERR_ReferenceComparison3 = 31080
ERR_CatchVariableNotLocal1 = 31082
ERR_ModuleMemberCantImplement = 31083
ERR_EventDelegatesCantBeFunctions = 31084
ERR_InvalidDate = 31085
ERR_CantOverride4 = 31086
ERR_CantSpecifyArraysOnBoth = 31087
ERR_NotOverridableRequiresOverrides = 31088
ERR_PrivateTypeOutsideType = 31089
ERR_TypeRefResolutionError3 = 31091
ERR_ParamArrayWrongType = 31092
ERR_CoClassMissing2 = 31094
ERR_InvalidMeReference = 31095
ERR_InvalidImplicitMeReference = 31096
ERR_RuntimeMemberNotFound2 = 31097
'ERR_RuntimeClassNotFound1 = 31098
ERR_BadPropertyAccessorFlags = 31099
ERR_BadPropertyAccessorFlagsRestrict = 31100
ERR_OnlyOneAccessorForGetSet = 31101
ERR_NoAccessibleSet = 31102
ERR_NoAccessibleGet = 31103
ERR_WriteOnlyNoAccessorFlag = 31104
ERR_ReadOnlyNoAccessorFlag = 31105
ERR_BadPropertyAccessorFlags1 = 31106
ERR_BadPropertyAccessorFlags2 = 31107
ERR_BadPropertyAccessorFlags3 = 31108
ERR_InAccessibleCoClass3 = 31109
ERR_MissingValuesForArraysInApplAttrs = 31110
ERR_ExitEventMemberNotInvalid = 31111
ERR_InvInsideEndsEvent = 31112
'ERR_EventMemberSyntax = 31113 abandoned per KevinH analysis. Roslyn bug 1637
ERR_MissingEndEvent = 31114
ERR_MissingEndAddHandler = 31115
ERR_MissingEndRemoveHandler = 31116
ERR_MissingEndRaiseEvent = 31117
'ERR_EndAddHandlerNotAtLineStart = 31118
'ERR_EndRemoveHandlerNotAtLineStart = 31119
'ERR_EndRaiseEventNotAtLineStart = 31120
ERR_CustomEventInvInInterface = 31121
ERR_CustomEventRequiresAs = 31122
ERR_InvalidEndEvent = 31123
ERR_InvalidEndAddHandler = 31124
ERR_InvalidEndRemoveHandler = 31125
ERR_InvalidEndRaiseEvent = 31126
ERR_DuplicateAddHandlerDef = 31127
ERR_DuplicateRemoveHandlerDef = 31128
ERR_DuplicateRaiseEventDef = 31129
ERR_MissingAddHandlerDef1 = 31130
ERR_MissingRemoveHandlerDef1 = 31131
ERR_MissingRaiseEventDef1 = 31132
ERR_EventAddRemoveHasOnlyOneParam = 31133
ERR_EventAddRemoveByrefParamIllegal = 31134
ERR_SpecifiersInvOnEventMethod = 31135
ERR_AddRemoveParamNotEventType = 31136
ERR_RaiseEventShapeMismatch1 = 31137
ERR_EventMethodOptionalParamIllegal1 = 31138
ERR_CantReferToMyGroupInsideGroupType1 = 31139
ERR_InvalidUseOfCustomModifier = 31140
ERR_InvalidOptionStrictCustom = 31141
ERR_ObsoleteInvalidOnEventMember = 31142
ERR_DelegateBindingIncompatible2 = 31143
ERR_ExpectedXmlName = 31146
ERR_UndefinedXmlPrefix = 31148
ERR_DuplicateXmlAttribute = 31149
ERR_MismatchedXmlEndTag = 31150
ERR_MissingXmlEndTag = 31151
ERR_ReservedXmlPrefix = 31152
ERR_MissingVersionInXmlDecl = 31153
ERR_IllegalAttributeInXmlDecl = 31154
ERR_QuotedEmbeddedExpression = 31155
ERR_VersionMustBeFirstInXmlDecl = 31156
ERR_AttributeOrder = 31157
'ERR_UnexpectedXmlName = 31158
ERR_ExpectedXmlEndEmbedded = 31159
ERR_ExpectedXmlEndPI = 31160
ERR_ExpectedXmlEndComment = 31161
ERR_ExpectedXmlEndCData = 31162
ERR_ExpectedSQuote = 31163
ERR_ExpectedQuote = 31164
ERR_ExpectedLT = 31165
ERR_StartAttributeValue = 31166
ERR_ExpectedDiv = 31167
ERR_NoXmlAxesLateBinding = 31168
ERR_IllegalXmlStartNameChar = 31169
ERR_IllegalXmlNameChar = 31170
ERR_IllegalXmlCommentChar = 31171
ERR_EmbeddedExpression = 31172
ERR_ExpectedXmlWhiteSpace = 31173
ERR_IllegalProcessingInstructionName = 31174
ERR_DTDNotSupported = 31175
'ERR_IllegalXmlChar = 31176 unused in Dev10
ERR_IllegalXmlWhiteSpace = 31177
ERR_ExpectedSColon = 31178
ERR_ExpectedXmlBeginEmbedded = 31179
ERR_XmlEntityReference = 31180
ERR_InvalidAttributeValue1 = 31181
ERR_InvalidAttributeValue2 = 31182
ERR_ReservedXmlNamespace = 31183
ERR_IllegalDefaultNamespace = 31184
'ERR_RequireAggregateInitializationImpl = 31185
ERR_QualifiedNameNotAllowed = 31186
ERR_ExpectedXmlns = 31187
'ERR_DefaultNamespaceNotSupported = 31188 Not reported by Dev10.
ERR_IllegalXmlnsPrefix = 31189
ERR_XmlFeaturesNotAvailable = 31190
'ERR_UnableToEmbedUacManifest = 31191 now reporting ErrorCreatingWin32ResourceFile
ERR_UnableToReadUacManifest2 = 31192
'ERR_UseValueForXmlExpression3 = 31193 ' Replaced by WRN_UseValueForXmlExpression3
ERR_TypeMismatchForXml3 = 31194
ERR_BinaryOperandsForXml4 = 31195
'ERR_XmlFeaturesNotAvailableDebugger = 31196
ERR_FullWidthAsXmlDelimiter = 31197
'ERR_XmlRequiresParens = 31198 No Longer Reported. Removed per 926946.
ERR_XmlEndCDataNotAllowedInContent = 31198
'ERR_UacALink3Missing = 31199 not used in Roslyn.
'ERR_XmlFeaturesNotSupported = 31200 not detected by the Roslyn compiler
ERR_EventImplRemoveHandlerParamWrong = 31201
ERR_MixingWinRTAndNETEvents = 31202
ERR_AddParamWrongForWinRT = 31203
ERR_RemoveParamWrongForWinRT = 31204
ERR_ReImplementingWinRTInterface5 = 31205
ERR_ReImplementingWinRTInterface4 = 31206
ERR_XmlEndElementNoMatchingStart = 31207
ERR_UndefinedTypeOrNamespace1 = 31208
ERR_BadInterfaceInterfaceSpecifier1 = 31209
ERR_TypeClashesWithVbCoreType4 = 31210
ERR_SecurityAttributeMissingAction = 31211
ERR_SecurityAttributeInvalidAction = 31212
ERR_SecurityAttributeInvalidActionAssembly = 31213
ERR_SecurityAttributeInvalidActionTypeOrMethod = 31214
ERR_PrincipalPermissionInvalidAction = 31215
ERR_PermissionSetAttributeInvalidFile = 31216
ERR_PermissionSetAttributeFileReadError = 31217
ERR_ExpectedWarningKeyword = 31218
ERR_InvalidHashAlgorithmName = 31219
'// NOTE: If you add any new errors that may be attached to a symbol during meta-import when it is marked as bad,
'// particularly if it applies to method symbols, please appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember.
'// Failure to do so may break customer code.
'// AVAILABLE 31220-31390
ERR_InvalidSubsystemVersion = 31391
ERR_LibAnycpu32bitPreferredConflict = 31392
ERR_RestrictedAccess = 31393
ERR_RestrictedConversion1 = 31394
ERR_NoTypecharInLabel = 31395
ERR_RestrictedType1 = 31396
ERR_NoTypecharInAlias = 31398
ERR_NoAccessibleConstructorOnBase = 31399
ERR_BadStaticLocalInStruct = 31400
ERR_DuplicateLocalStatic1 = 31401
ERR_ImportAliasConflictsWithType2 = 31403
ERR_CantShadowAMustOverride1 = 31404
'ERR_OptionalsCantBeStructs = 31405
ERR_MultipleEventImplMismatch3 = 31407
ERR_BadSpecifierCombo2 = 31408
ERR_MustBeOverloads2 = 31409
'ERR_CantOverloadOnMultipleInheritance = 31410
ERR_MustOverridesInClass1 = 31411
ERR_HandlesSyntaxInClass = 31412
ERR_SynthMemberShadowsMustOverride5 = 31413
'ERR_CantImplementNonVirtual3 = 31415 unused in Roslyn
' ERR_MemberShadowsSynthMustOverride5 = 31416 unused in Roslyn
ERR_CannotOverrideInAccessibleMember = 31417
ERR_HandlesSyntaxInModule = 31418
ERR_IsNotOpRequiresReferenceTypes1 = 31419
ERR_ClashWithReservedEnumMember1 = 31420
ERR_MultiplyDefinedEnumMember2 = 31421
ERR_BadUseOfVoid = 31422
ERR_EventImplMismatch5 = 31423
ERR_ForwardedTypeUnavailable3 = 31424
ERR_TypeFwdCycle2 = 31425
ERR_BadTypeInCCExpression = 31426
ERR_BadCCExpression = 31427
ERR_VoidArrayDisallowed = 31428
ERR_MetadataMembersAmbiguous3 = 31429
ERR_TypeOfExprAlwaysFalse2 = 31430
ERR_OnlyPrivatePartialMethods1 = 31431
ERR_PartialMethodsMustBePrivate = 31432
ERR_OnlyOnePartialMethodAllowed2 = 31433
ERR_OnlyOneImplementingMethodAllowed3 = 31434
ERR_PartialMethodMustBeEmpty = 31435
ERR_PartialMethodsMustBeSub1 = 31437
ERR_PartialMethodGenericConstraints2 = 31438
ERR_PartialDeclarationImplements1 = 31439
ERR_NoPartialMethodInAddressOf1 = 31440
ERR_ImplementationMustBePrivate2 = 31441
ERR_PartialMethodParamNamesMustMatch3 = 31442
ERR_PartialMethodTypeParamNameMismatch3 = 31443
ERR_PropertyDoesntImplementAllAccessors = 31444
ERR_InvalidAttributeUsageOnAccessor = 31445
ERR_NestedTypeInInheritsClause2 = 31446
ERR_TypeInItsInheritsClause1 = 31447
ERR_BaseTypeReferences2 = 31448
ERR_IllegalBaseTypeReferences3 = 31449
ERR_InvalidCoClass1 = 31450
ERR_InvalidOutputName = 31451
ERR_InvalidFileAlignment = 31452
ERR_InvalidDebugInformationFormat = 31453
'// NOTE: If you add any new errors that may be attached to a symbol during meta-import when it is marked as bad,
'// particularly if it applies to method symbols, please appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember.
'// Failure to do so may break customer code.
'// AVAILABLE 31451 - 31497
ERR_ConstantStringTooLong = 31498
ERR_MustInheritEventNotOverridden = 31499
ERR_BadAttributeSharedProperty1 = 31500
ERR_BadAttributeReadOnlyProperty1 = 31501
ERR_DuplicateResourceName1 = 31502
ERR_AttributeMustBeClassNotStruct1 = 31503
ERR_AttributeMustInheritSysAttr = 31504
'ERR_AttributeMustHaveAttrUsageAttr = 31505 unused in Roslyn.
ERR_AttributeCannotBeAbstract = 31506
' ERR_AttributeCannotHaveMustOverride = 31507 - reported by dev10 but error is redundant. ERR_AttributeCannotBeAbstract covers this case.
'ERR_CantFindCORSystemDirectory = 31508
ERR_UnableToOpenResourceFile1 = 31509
'ERR_BadAttributeConstField1 = 31510
ERR_BadAttributeNonPublicProperty1 = 31511
ERR_STAThreadAndMTAThread0 = 31512
'ERR_STAThreadAndMTAThread1 = 31513
'//If you make any change involving this error, such as creating a more specific version for use
'//in a particular context, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
ERR_IndirectUnreferencedAssembly4 = 31515
ERR_BadAttributeNonPublicType1 = 31516
ERR_BadAttributeNonPublicContType2 = 31517
'ERR_AlinkManifestFilepathTooLong = 31518 this scenario reports a more generic error
ERR_BadMetaDataReference1 = 31519
' ERR_ErrorApplyingSecurityAttribute1 = 31520 ' ' we're now reporting more detailed diagnostics: ERR_SecurityAttributeMissingAction, ERR_SecurityAttributeInvalidAction, ERR_SecurityAttributeInvalidActionAssembly or ERR_SecurityAttributeInvalidActionTypeOrMethod
'ERR_DuplicateModuleAttribute1 = 31521
ERR_DllImportOnNonEmptySubOrFunction = 31522
ERR_DllImportNotLegalOnDeclare = 31523
ERR_DllImportNotLegalOnGetOrSet = 31524
'ERR_TypeImportedFromDiffAssemVersions3 = 31525
ERR_DllImportOnGenericSubOrFunction = 31526
ERR_ComClassOnGeneric = 31527
'//If you make any change involving this error, such as creating a more specific version for use
'//in a particular context, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
'ERR_IndirectUnreferencedAssembly3 = 31528
ERR_DllImportOnInstanceMethod = 31529
ERR_DllImportOnInterfaceMethod = 31530
ERR_DllImportNotLegalOnEventMethod = 31531
'//If you make any change involving these errors, such as creating more specific versions for use
'//in other contexts, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
'ERR_IndirectUnreferencedProject3 = 31532
'ERR_IndirectUnreferencedProject2 = 31533
ERR_FriendAssemblyBadArguments = 31534
ERR_FriendAssemblyStrongNameRequired = 31535
'ERR_FriendAssemblyRejectBinding = 31536 EDMAURER This has been replaced with two, more specific errors ERR_FriendRefNotEqualToThis and ERR_FriendRefSigningMismatch.
ERR_FriendAssemblyNameInvalid = 31537
ERR_FriendAssemblyBadAccessOverride2 = 31538
ERR_AbsentReferenceToPIA1 = 31539
'ERR_CorlibMissingPIAClasses1 = 31540 EDMAURER Roslyn uses the ordinary missing required type message
ERR_CannotLinkClassWithNoPIA1 = 31541
ERR_InvalidStructMemberNoPIA1 = 31542
ERR_NoPIAAttributeMissing2 = 31543
ERR_NestedGlobalNamespace = 31544
'ERR_NewCoClassNoPIA = 31545 EDMAURER Roslyn gives 31541
'ERR_EventNoPIANoDispID = 31546
'ERR_EventNoPIANoGuid1 = 31547
'ERR_EventNoPIANoComEventInterface1 = 31548
ERR_PIAHasNoAssemblyGuid1 = 31549
'ERR_StructureExplicitFieldLacksOffset = 31550
'ERR_CannotLinkEventInterfaceWithNoPIA1 = 31551
ERR_DuplicateLocalTypes3 = 31552
ERR_PIAHasNoTypeLibAttribute1 = 31553
' ERR_NoPiaEventsMissingSystemCore = 31554 use ordinary missing required type
' ERR_SourceInterfaceMustExist = 31555
ERR_SourceInterfaceMustBeInterface = 31556
ERR_EventNoPIANoBackingMember = 31557
ERR_NestedInteropType = 31558 ' used to be ERR_InvalidInteropType
ERR_IsNestedIn2 = 31559
ERR_LocalTypeNameClash2 = 31560
ERR_InteropMethodWithBody1 = 31561
ERR_UseOfLocalBeforeDeclaration1 = 32000
ERR_UseOfKeywordFromModule1 = 32001
'ERR_UseOfKeywordOutsideClass1 = 32002
'ERR_SymbolFromUnreferencedProject3 = 32004
ERR_BogusWithinLineIf = 32005
ERR_CharToIntegralTypeMismatch1 = 32006
ERR_IntegralToCharTypeMismatch1 = 32007
ERR_NoDirectDelegateConstruction1 = 32008
ERR_MethodMustBeFirstStatementOnLine = 32009
ERR_AttrAssignmentNotFieldOrProp1 = 32010
ERR_StrictDisallowsObjectComparison1 = 32013
ERR_NoConstituentArraySizes = 32014
ERR_FileAttributeNotAssemblyOrModule = 32015
ERR_FunctionResultCannotBeIndexed1 = 32016
ERR_ArgumentSyntax = 32017
ERR_ExpectedResumeOrGoto = 32019
ERR_ExpectedAssignmentOperator = 32020
ERR_NamedArgAlsoOmitted2 = 32021
ERR_CannotCallEvent1 = 32022
ERR_ForEachCollectionDesignPattern1 = 32023
ERR_DefaultValueForNonOptionalParam = 32024
' ERR_RegionWithinMethod = 32025 removed this limitation in Roslyn
'ERR_SpecifiersInvalidOnNamespace = 32026 abandoned, now giving 'Specifiers and attributes are not valid on this statement.'
ERR_ExpectedDotAfterMyBase = 32027
ERR_ExpectedDotAfterMyClass = 32028
ERR_StrictArgumentCopyBackNarrowing3 = 32029
ERR_LbElseifAfterElse = 32030
'ERR_EndSubNotAtLineStart = 32031
'ERR_EndFunctionNotAtLineStart = 32032
'ERR_EndGetNotAtLineStart = 32033
'ERR_EndSetNotAtLineStart = 32034
ERR_StandaloneAttribute = 32035
ERR_NoUniqueConstructorOnBase2 = 32036
ERR_ExtraNextVariable = 32037
ERR_RequiredNewCallTooMany2 = 32038
ERR_ForCtlVarArraySizesSpecified = 32039
ERR_BadFlagsOnNewOverloads = 32040
ERR_TypeCharOnGenericParam = 32041
ERR_TooFewGenericArguments1 = 32042
ERR_TooManyGenericArguments1 = 32043
ERR_GenericConstraintNotSatisfied2 = 32044
ERR_TypeOrMemberNotGeneric1 = 32045
ERR_NewIfNullOnGenericParam = 32046
ERR_MultipleClassConstraints1 = 32047
ERR_ConstNotClassInterfaceOrTypeParam1 = 32048
ERR_DuplicateTypeParamName1 = 32049
ERR_UnboundTypeParam2 = 32050
ERR_IsOperatorGenericParam1 = 32052
ERR_ArgumentCopyBackNarrowing3 = 32053
ERR_ShadowingGenericParamWithMember1 = 32054
ERR_GenericParamBase2 = 32055
ERR_ImplementsGenericParam = 32056
'ERR_ExpressionCannotBeGeneric1 = 32058 unused in Roslyn
ERR_OnlyNullLowerBound = 32059
ERR_ClassConstraintNotInheritable1 = 32060
ERR_ConstraintIsRestrictedType1 = 32061
ERR_GenericParamsOnInvalidMember = 32065
ERR_GenericArgsOnAttributeSpecifier = 32066
ERR_AttrCannotBeGenerics = 32067
ERR_BadStaticLocalInGenericMethod = 32068
ERR_SyntMemberShadowsGenericParam3 = 32070
ERR_ConstraintAlreadyExists1 = 32071
ERR_InterfacePossiblyImplTwice2 = 32072
ERR_ModulesCannotBeGeneric = 32073
ERR_GenericClassCannotInheritAttr = 32074
ERR_DeclaresCantBeInGeneric = 32075
'ERR_GenericTypeRequiresTypeArgs1 = 32076
ERR_OverrideWithConstraintMismatch2 = 32077
ERR_ImplementsWithConstraintMismatch3 = 32078
ERR_OpenTypeDisallowed = 32079
ERR_HandlesInvalidOnGenericMethod = 32080
ERR_MultipleNewConstraints = 32081
ERR_MustInheritForNewConstraint2 = 32082
ERR_NoSuitableNewForNewConstraint2 = 32083
ERR_BadGenericParamForNewConstraint2 = 32084
ERR_NewArgsDisallowedForTypeParam = 32085
ERR_DuplicateRawGenericTypeImport1 = 32086
ERR_NoTypeArgumentCountOverloadCand1 = 32087
ERR_TypeArgsUnexpected = 32088
ERR_NameSameAsMethodTypeParam1 = 32089
ERR_TypeParamNameFunctionNameCollision = 32090
'ERR_OverloadsMayUnify2 = 32091 unused in Roslyn
ERR_BadConstraintSyntax = 32092
ERR_OfExpected = 32093
ERR_ArrayOfRawGenericInvalid = 32095
ERR_ForEachAmbiguousIEnumerable1 = 32096
ERR_IsNotOperatorGenericParam1 = 32097
ERR_TypeParamQualifierDisallowed = 32098
ERR_TypeParamMissingCommaOrRParen = 32099
ERR_TypeParamMissingAsCommaOrRParen = 32100
ERR_MultipleReferenceConstraints = 32101
ERR_MultipleValueConstraints = 32102
ERR_NewAndValueConstraintsCombined = 32103
ERR_RefAndValueConstraintsCombined = 32104
ERR_BadTypeArgForStructConstraint2 = 32105
ERR_BadTypeArgForRefConstraint2 = 32106
ERR_RefAndClassTypeConstrCombined = 32107
ERR_ValueAndClassTypeConstrCombined = 32108
ERR_ConstraintClashIndirectIndirect4 = 32109
ERR_ConstraintClashDirectIndirect3 = 32110
ERR_ConstraintClashIndirectDirect3 = 32111
ERR_ConstraintCycleLink2 = 32112
ERR_ConstraintCycle2 = 32113
ERR_TypeParamWithStructConstAsConst = 32114
ERR_NullableDisallowedForStructConstr1 = 32115
'ERR_NoAccessibleNonGeneric1 = 32117
'ERR_NoAccessibleGeneric1 = 32118
ERR_ConflictingDirectConstraints3 = 32119
ERR_InterfaceUnifiesWithInterface2 = 32120
ERR_BaseUnifiesWithInterfaces3 = 32121
ERR_InterfaceBaseUnifiesWithBase4 = 32122
ERR_InterfaceUnifiesWithBase3 = 32123
ERR_OptionalsCantBeStructGenericParams = 32124 'TODO: remove
'ERR_InterfaceMethodImplsUnify3 = 32125
ERR_AddressOfNullableMethod = 32126
ERR_IsOperatorNullable1 = 32127
ERR_IsNotOperatorNullable1 = 32128
'ERR_NullableOnEnum = 32129
'ERR_NoNullableType = 32130 unused in Roslyn
ERR_ClassInheritsBaseUnifiesWithInterfaces3 = 32131
ERR_ClassInheritsInterfaceBaseUnifiesWithBase4 = 32132
ERR_ClassInheritsInterfaceUnifiesWithBase3 = 32133
ERR_ShadowingTypeOutsideClass1 = 32200
ERR_PropertySetParamCollisionWithValue = 32201
'ERR_EventNameTooLong = 32204 ' Deprecated in favor of ERR_TooLongMetadataName
'ERR_WithEventsNameTooLong = 32205 ' Deprecated in favor of ERR_TooLongMetadataName
ERR_SxSIndirectRefHigherThanDirectRef3 = 32207
ERR_DuplicateReference2 = 32208
'ERR_SxSLowerVerIndirectRefNotEmitted4 = 32209 not used in Roslyn
ERR_DuplicateReferenceStrong = 32210
ERR_IllegalCallOrIndex = 32303
ERR_ConflictDefaultPropertyAttribute = 32304
'ERR_ClassCannotCreated = 32400
ERR_BadAttributeUuid2 = 32500
ERR_ComClassAndReservedAttribute1 = 32501
ERR_ComClassRequiresPublicClass2 = 32504
ERR_ComClassReservedDispIdZero1 = 32505
ERR_ComClassReservedDispId1 = 32506
ERR_ComClassDuplicateGuids1 = 32507
ERR_ComClassCantBeAbstract0 = 32508
ERR_ComClassRequiresPublicClass1 = 32509
'ERR_DefaultCharSetAttributeNotSupported = 32510
ERR_UnknownOperator = 33000
ERR_DuplicateConversionCategoryUsed = 33001
ERR_OperatorNotOverloadable = 33002
ERR_InvalidHandles = 33003
ERR_InvalidImplements = 33004
ERR_EndOperatorExpected = 33005
ERR_EndOperatorNotAtLineStart = 33006
ERR_InvalidEndOperator = 33007
ERR_ExitOperatorNotValid = 33008
ERR_ParamArrayIllegal1 = 33009
ERR_OptionalIllegal1 = 33010
ERR_OperatorMustBePublic = 33011
ERR_OperatorMustBeShared = 33012
ERR_BadOperatorFlags1 = 33013
ERR_OneParameterRequired1 = 33014
ERR_TwoParametersRequired1 = 33015
ERR_OneOrTwoParametersRequired1 = 33016
ERR_ConvMustBeWideningOrNarrowing = 33017
ERR_OperatorDeclaredInModule = 33018
ERR_InvalidSpecifierOnNonConversion1 = 33019
ERR_UnaryParamMustBeContainingType1 = 33020
ERR_BinaryParamMustBeContainingType1 = 33021
ERR_ConvParamMustBeContainingType1 = 33022
ERR_OperatorRequiresBoolReturnType1 = 33023
ERR_ConversionToSameType = 33024
ERR_ConversionToInterfaceType = 33025
ERR_ConversionToBaseType = 33026
ERR_ConversionToDerivedType = 33027
ERR_ConversionToObject = 33028
ERR_ConversionFromInterfaceType = 33029
ERR_ConversionFromBaseType = 33030
ERR_ConversionFromDerivedType = 33031
ERR_ConversionFromObject = 33032
ERR_MatchingOperatorExpected2 = 33033
ERR_UnacceptableLogicalOperator3 = 33034
ERR_ConditionOperatorRequired3 = 33035
ERR_CopyBackTypeMismatch3 = 33037
ERR_ForLoopOperatorRequired2 = 33038
ERR_UnacceptableForLoopOperator2 = 33039
ERR_UnacceptableForLoopRelOperator2 = 33040
ERR_OperatorRequiresIntegerParameter1 = 33041
ERR_CantSpecifyNullableOnBoth = 33100
ERR_BadTypeArgForStructConstraintNull = 33101
ERR_CantSpecifyArrayAndNullableOnBoth = 33102
ERR_CantSpecifyTypeCharacterOnIIF = 33103
ERR_IllegalOperandInIIFCount = 33104
ERR_IllegalOperandInIIFName = 33105
ERR_IllegalOperandInIIFConversion = 33106
ERR_IllegalCondTypeInIIF = 33107
ERR_CantCallIIF = 33108
ERR_CantSpecifyAsNewAndNullable = 33109
ERR_IllegalOperandInIIFConversion2 = 33110
ERR_BadNullTypeInCCExpression = 33111
ERR_NullableImplicit = 33112
'// NOTE: If you add any new errors that may be attached to a symbol during meta-import when it is marked as bad,
'// particularly if it applies to method symbols, please appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember.
'// Failure to do so may break customer code.
'// AVAILABLE 33113 - 34999
ERR_MissingRuntimeHelper = 35000
'ERR_NoStdModuleAttribute = 35001 ' Note: we're now reporting a use site error in this case.
'ERR_NoOptionTextAttribute = 35002
ERR_DuplicateResourceFileName1 = 35003
ERR_ExpectedDotAfterGlobalNameSpace = 36000
ERR_NoGlobalExpectedIdentifier = 36001
ERR_NoGlobalInHandles = 36002
ERR_ElseIfNoMatchingIf = 36005
ERR_BadAttributeConstructor2 = 36006
ERR_EndUsingWithoutUsing = 36007
ERR_ExpectedEndUsing = 36008
ERR_GotoIntoUsing = 36009
ERR_UsingRequiresDisposePattern = 36010
ERR_UsingResourceVarNeedsInitializer = 36011
ERR_UsingResourceVarCantBeArray = 36012
ERR_OnErrorInUsing = 36013
ERR_PropertyNameConflictInMyCollection = 36015
ERR_InvalidImplicitVar = 36016
ERR_ObjectInitializerRequiresFieldName = 36530
ERR_ExpectedFrom = 36531
ERR_LambdaBindingMismatch1 = 36532
ERR_CannotLiftByRefParamQuery1 = 36533
ERR_ExpressionTreeNotSupported = 36534
ERR_CannotLiftStructureMeQuery = 36535
ERR_InferringNonArrayType1 = 36536
ERR_ByRefParamInExpressionTree = 36538
'ERR_ObjectInitializerBadValue = 36543
'// If you change this message, make sure to change message for QueryDuplicateAnonTypeMemberName1 as well!
ERR_DuplicateAnonTypeMemberName1 = 36547
ERR_BadAnonymousTypeForExprTree = 36548
ERR_CannotLiftAnonymousType1 = 36549
ERR_ExtensionOnlyAllowedOnModuleSubOrFunction = 36550
ERR_ExtensionMethodNotInModule = 36551
ERR_ExtensionMethodNoParams = 36552
ERR_ExtensionMethodOptionalFirstArg = 36553
ERR_ExtensionMethodParamArrayFirstArg = 36554
'// If you change this message, make sure to change message for QueryAnonymousTypeFieldNameInference as well!
'ERR_BadOrCircularInitializerReference = 36555
ERR_AnonymousTypeFieldNameInference = 36556
ERR_NameNotMemberOfAnonymousType2 = 36557
ERR_ExtensionAttributeInvalid = 36558
ERR_AnonymousTypePropertyOutOfOrder1 = 36559
'// If you change this message, make sure to change message for QueryAnonymousTypeDisallowsTypeChar as well!
ERR_AnonymousTypeDisallowsTypeChar = 36560
ERR_ExtensionMethodUncallable1 = 36561
ERR_ExtensionMethodOverloadCandidate3 = 36562
ERR_DelegateBindingMismatch = 36563
ERR_DelegateBindingTypeInferenceFails = 36564
ERR_TooManyArgs = 36565
ERR_NamedArgAlsoOmitted1 = 36566
ERR_NamedArgUsedTwice1 = 36567
ERR_NamedParamNotFound1 = 36568
ERR_OmittedArgument1 = 36569
ERR_UnboundTypeParam1 = 36572
ERR_ExtensionMethodOverloadCandidate2 = 36573
ERR_AnonymousTypeNeedField = 36574
ERR_AnonymousTypeNameWithoutPeriod = 36575
ERR_AnonymousTypeExpectedIdentifier = 36576
'ERR_NoAnonymousTypeInitializersInDebugger = 36577
'ERR_TooFewGenericArguments = 36578
'ERR_TooManyGenericArguments = 36579
'ERR_DelegateBindingMismatch3_3 = 36580 unused in Roslyn
'ERR_DelegateBindingTypeInferenceFails3 = 36581
ERR_TooManyArgs2 = 36582
ERR_NamedArgAlsoOmitted3 = 36583
ERR_NamedArgUsedTwice3 = 36584
ERR_NamedParamNotFound3 = 36585
ERR_OmittedArgument3 = 36586
ERR_UnboundTypeParam3 = 36589
ERR_TooFewGenericArguments2 = 36590
ERR_TooManyGenericArguments2 = 36591
ERR_ExpectedInOrEq = 36592
ERR_ExpectedQueryableSource = 36593
ERR_QueryOperatorNotFound = 36594
ERR_CannotUseOnErrorGotoWithClosure = 36595
ERR_CannotGotoNonScopeBlocksWithClosure = 36597
ERR_CannotLiftRestrictedTypeQuery = 36598
ERR_QueryAnonymousTypeFieldNameInference = 36599
ERR_QueryDuplicateAnonTypeMemberName1 = 36600
ERR_QueryAnonymousTypeDisallowsTypeChar = 36601
ERR_ReadOnlyInClosure = 36602
ERR_ExprTreeNoMultiDimArrayCreation = 36603
ERR_ExprTreeNoLateBind = 36604
ERR_ExpectedBy = 36605
ERR_QueryInvalidControlVariableName1 = 36606
ERR_ExpectedIn = 36607
'ERR_QueryStartsWithLet = 36608
'ERR_NoQueryExpressionsInDebugger = 36609
ERR_QueryNameNotDeclared = 36610
ERR_SharedEventNeedsHandlerInTheSameType = 36611
ERR_NestedFunctionArgumentNarrowing3 = 36612
'// If you change this message, make sure to change message for QueryAnonTypeFieldXMLNameInference as well!
ERR_AnonTypeFieldXMLNameInference = 36613
ERR_QueryAnonTypeFieldXMLNameInference = 36614
ERR_ExpectedInto = 36615
'ERR_AggregateStartsWithLet = 36616
ERR_TypeCharOnAggregation = 36617
ERR_ExpectedOn = 36618
ERR_ExpectedEquals = 36619
ERR_ExpectedAnd = 36620
ERR_EqualsTypeMismatch = 36621
ERR_EqualsOperandIsBad = 36622
'// see 30581 (lambda version of addressof)
ERR_LambdaNotDelegate1 = 36625
'// see 30939 (lambda version of addressof)
ERR_LambdaNotCreatableDelegate1 = 36626
'ERR_NoLambdaExpressionsInDebugger = 36627
ERR_CannotInferNullableForVariable1 = 36628
ERR_NullableTypeInferenceNotSupported = 36629
ERR_ExpectedJoin = 36631
ERR_NullableParameterMustSpecifyType = 36632
ERR_IterationVariableShadowLocal2 = 36633
ERR_LambdasCannotHaveAttributes = 36634
ERR_LambdaInSelectCaseExpr = 36635
ERR_AddressOfInSelectCaseExpr = 36636
ERR_NullableCharNotSupported = 36637
'// The follow error messages are paired with other query specific messages above. Please
'// make sure to keep the two in sync
ERR_CannotLiftStructureMeLambda = 36638
ERR_CannotLiftByRefParamLambda1 = 36639
ERR_CannotLiftRestrictedTypeLambda = 36640
ERR_LambdaParamShadowLocal1 = 36641
ERR_StrictDisallowImplicitObjectLambda = 36642
ERR_CantSpecifyParamsOnLambdaParamNoType = 36643
ERR_TypeInferenceFailure1 = 36644
ERR_TypeInferenceFailure2 = 36645
ERR_TypeInferenceFailure3 = 36646
ERR_TypeInferenceFailureNoExplicit1 = 36647
ERR_TypeInferenceFailureNoExplicit2 = 36648
ERR_TypeInferenceFailureNoExplicit3 = 36649
ERR_TypeInferenceFailureAmbiguous1 = 36650
ERR_TypeInferenceFailureAmbiguous2 = 36651
ERR_TypeInferenceFailureAmbiguous3 = 36652
ERR_TypeInferenceFailureNoExplicitAmbiguous1 = 36653
ERR_TypeInferenceFailureNoExplicitAmbiguous2 = 36654
ERR_TypeInferenceFailureNoExplicitAmbiguous3 = 36655
ERR_TypeInferenceFailureNoBest1 = 36656
ERR_TypeInferenceFailureNoBest2 = 36657
ERR_TypeInferenceFailureNoBest3 = 36658
ERR_TypeInferenceFailureNoExplicitNoBest1 = 36659
ERR_TypeInferenceFailureNoExplicitNoBest2 = 36660
ERR_TypeInferenceFailureNoExplicitNoBest3 = 36661
ERR_DelegateBindingMismatchStrictOff2 = 36663
'ERR_TooDeepNestingOfParensInLambdaParam = 36664 - No Longer Reported. Removed per 926942
' ERR_InaccessibleReturnTypeOfSymbol1 = 36665
ERR_InaccessibleReturnTypeOfMember2 = 36666
ERR_LocalNamedSameAsParamInLambda1 = 36667
ERR_MultilineLambdasCannotContainOnError = 36668
'ERR_BranchOutOfMultilineLambda = 36669 obsolete - was not even reported in Dev10 any more.
ERR_LambdaBindingMismatch2 = 36670
'ERR_MultilineLambdaShadowLocal1 = 36671 'unused in Roslyn
ERR_StaticInLambda = 36672
ERR_MultilineLambdaMissingSub = 36673
ERR_MultilineLambdaMissingFunction = 36674
ERR_StatementLambdaInExpressionTree = 36675
' //ERR_StrictDisallowsImplicitLambda = 36676
' // replaced by LambdaNoType and LambdaNoTypeObjectDisallowed and LambdaTooManyTypesObjectDisallowed
ERR_AttributeOnLambdaReturnType = 36677
ERR_ExpectedIdentifierOrGroup = 36707
ERR_UnexpectedGroup = 36708
ERR_DelegateBindingMismatchStrictOff3 = 36709
ERR_DelegateBindingIncompatible3 = 36710
ERR_ArgumentNarrowing2 = 36711
ERR_OverloadCandidate1 = 36712
ERR_AutoPropertyInitializedInStructure = 36713
ERR_InitializedExpandedProperty = 36714
'ERR_NewExpandedProperty = 36715 'unused in Roslyn
ERR_LanguageVersion = 36716
ERR_ArrayInitNoType = 36717
ERR_NotACollection1 = 36718
ERR_NoAddMethod1 = 36719
ERR_CantCombineInitializers = 36720
ERR_EmptyAggregateInitializer = 36721
ERR_VarianceDisallowedHere = 36722
ERR_VarianceInterfaceNesting = 36723
ERR_VarianceOutParamDisallowed1 = 36724
ERR_VarianceInParamDisallowed1 = 36725
ERR_VarianceOutParamDisallowedForGeneric3 = 36726
ERR_VarianceInParamDisallowedForGeneric3 = 36727
ERR_VarianceOutParamDisallowedHere2 = 36728
ERR_VarianceInParamDisallowedHere2 = 36729
ERR_VarianceOutParamDisallowedHereForGeneric4 = 36730
ERR_VarianceInParamDisallowedHereForGeneric4 = 36731
ERR_VarianceTypeDisallowed2 = 36732
ERR_VarianceTypeDisallowedForGeneric4 = 36733
ERR_LambdaTooManyTypesObjectDisallowed = 36734
ERR_VarianceTypeDisallowedHere3 = 36735
ERR_VarianceTypeDisallowedHereForGeneric5 = 36736
ERR_AmbiguousCastConversion2 = 36737
ERR_VariancePreventsSynthesizedEvents2 = 36738
ERR_NestingViolatesCLS1 = 36739
ERR_VarianceOutNullableDisallowed2 = 36740
ERR_VarianceInNullableDisallowed2 = 36741
ERR_VarianceOutByValDisallowed1 = 36742
ERR_VarianceInReturnDisallowed1 = 36743
ERR_VarianceOutConstraintDisallowed1 = 36744
ERR_VarianceInReadOnlyPropertyDisallowed1 = 36745
ERR_VarianceOutWriteOnlyPropertyDisallowed1 = 36746
ERR_VarianceOutPropertyDisallowed1 = 36747
ERR_VarianceInPropertyDisallowed1 = 36748
ERR_VarianceOutByRefDisallowed1 = 36749
ERR_VarianceInByRefDisallowed1 = 36750
ERR_LambdaNoType = 36751
' //ERR_NoReturnStatementsForMultilineLambda = 36752
' // replaced by LambdaNoType and LambdaNoTypeObjectDisallowed
'ERR_CollectionInitializerArity2 = 36753
ERR_VarianceConversionFailedOut6 = 36754
ERR_VarianceConversionFailedIn6 = 36755
ERR_VarianceIEnumerableSuggestion3 = 36756
ERR_VarianceConversionFailedTryOut4 = 36757
ERR_VarianceConversionFailedTryIn4 = 36758
ERR_AutoPropertyCantHaveParams = 36759
ERR_IdentityDirectCastForFloat = 36760
ERR_TypeDisallowsElements = 36807
ERR_TypeDisallowsAttributes = 36808
ERR_TypeDisallowsDescendants = 36809
'ERR_XmlSchemaCompileError = 36810
ERR_TypeOrMemberNotGeneric2 = 36907
ERR_ExtensionMethodCannotBeLateBound = 36908
ERR_TypeInferenceArrayRankMismatch1 = 36909
ERR_QueryStrictDisallowImplicitObject = 36910
ERR_IfNoType = 36911
ERR_IfNoTypeObjectDisallowed = 36912
ERR_IfTooManyTypesObjectDisallowed = 36913
ERR_ArrayInitNoTypeObjectDisallowed = 36914
ERR_ArrayInitTooManyTypesObjectDisallowed = 36915
ERR_LambdaNoTypeObjectDisallowed = 36916
ERR_OverloadsModifierInModule = 36917
ERR_SubRequiresSingleStatement = 36918
ERR_SubDisallowsStatement = 36919
ERR_SubRequiresParenthesesLParen = 36920
ERR_SubRequiresParenthesesDot = 36921
ERR_SubRequiresParenthesesBang = 36922
ERR_CannotEmbedInterfaceWithGeneric = 36923
ERR_CannotUseGenericTypeAcrossAssemblyBoundaries = 36924
ERR_CannotUseGenericBaseTypeAcrossAssemblyBoundaries = 36925
ERR_BadAsyncByRefParam = 36926
ERR_BadIteratorByRefParam = 36927
'ERR_BadAsyncExpressionLambda = 36928 'unused in Roslyn
ERR_BadAsyncInQuery = 36929
ERR_BadGetAwaiterMethod1 = 36930
'ERR_ExpressionTreeContainsAwait = 36931
ERR_RestrictedResumableType1 = 36932
ERR_BadAwaitNothing = 36933
ERR_AsyncSubMain = 36934
ERR_PartialMethodsMustNotBeAsync1 = 36935
ERR_InvalidAsyncIteratorModifiers = 36936
ERR_BadAwaitNotInAsyncMethodOrLambda = 36937
ERR_BadIteratorReturn = 36938
ERR_BadYieldInTryHandler = 36939
ERR_BadYieldInNonIteratorMethod = 36940
'// unused 36941
ERR_BadReturnValueInIterator = 36942
ERR_BadAwaitInTryHandler = 36943
'ERR_BadAwaitObject = 36944 'unused in Roslyn
ERR_BadAsyncReturn = 36945
ERR_BadResumableAccessReturnVariable = 36946
ERR_BadIteratorExpressionLambda = 36947
'ERR_AwaitLibraryMissing = 36948
'ERR_AwaitPattern1 = 36949
ERR_ConstructorAsync = 36950
ERR_InvalidLambdaModifier = 36951
ERR_ReturnFromNonGenericTaskAsync = 36952
'ERR_BadAutoPropertyFlags1 = 36953 'unused in Roslyn
ERR_BadOverloadCandidates2 = 36954
ERR_BadStaticInitializerInResumable = 36955
ERR_ResumablesCannotContainOnError = 36956
ERR_FriendRefNotEqualToThis = 36957
ERR_FriendRefSigningMismatch = 36958
ERR_FailureSigningAssembly = 36960
ERR_SignButNoPrivateKey = 36961
ERR_InvalidVersionFormat = 36962
ERR_ExpectedSingleScript = 36963
ERR_ReferenceDirectiveOnlyAllowedInScripts = 36964
ERR_NamespaceNotAllowedInScript = 36965
ERR_KeywordNotAllowedInScript = 36966
ERR_ReservedAssemblyName = 36968
ERR_ConstructorCannotBeDeclaredPartial = 36969
ERR_ModuleEmitFailure = 36970
ERR_ParameterNotValidForType = 36971
ERR_MarshalUnmanagedTypeNotValidForFields = 36972
ERR_MarshalUnmanagedTypeOnlyValidForFields = 36973
ERR_AttributeParameterRequired1 = 36974
ERR_AttributeParameterRequired2 = 36975
ERR_InvalidVersionFormat2 = 36976
ERR_InvalidAssemblyCultureForExe = 36977
ERR_InvalidMultipleAttributeUsageInNetModule2 = 36978
ERR_SecurityAttributeInvalidTarget = 36979
ERR_PublicKeyFileFailure = 36980
ERR_PublicKeyContainerFailure = 36981
ERR_InvalidAssemblyCulture = 36982
ERR_EncUpdateFailedMissingAttribute = 36983
ERR_CantAwaitAsyncSub1 = 37001
ERR_ResumableLambdaInExpressionTree = 37050
ERR_DllImportOnResumableMethod = 37051
ERR_CannotLiftRestrictedTypeResumable1 = 37052
ERR_BadIsCompletedOnCompletedGetResult2 = 37053
ERR_SynchronizedAsyncMethod = 37054
ERR_BadAsyncReturnOperand1 = 37055
ERR_DoesntImplementAwaitInterface2 = 37056
ERR_BadAwaitInNonAsyncMethod = 37057
ERR_BadAwaitInNonAsyncVoidMethod = 37058
ERR_BadAwaitInNonAsyncLambda = 37059
ERR_LoopControlMustNotAwait = 37060
ERR_MyGroupCollectionAttributeCycle = 37201
ERR_LiteralExpected = 37202
ERR_PartialMethodDefaultParameterValueMismatch2 = 37203
ERR_PartialMethodParamArrayMismatch2 = 37204
ERR_NetModuleNameMismatch = 37205
ERR_BadModuleName = 37206
ERR_CmdOptionConflictsSource = 37207
ERR_TypeForwardedToMultipleAssemblies = 37208
ERR_InvalidSignaturePublicKey = 37209
ERR_CollisionWithPublicTypeInModule = 37210
ERR_ExportedTypeConflictsWithDeclaration = 37211
ERR_ExportedTypesConflict = 37212
ERR_AgnosticToMachineModule = 37213
ERR_ConflictingMachineModule = 37214
ERR_CryptoHashFailed = 37215
ERR_CantHaveWin32ResAndManifest = 37216
ERR_ForwardedTypeConflictsWithDeclaration = 37217
ERR_ForwardedTypeConflictsWithExportedType = 37218
ERR_ForwardedTypesConflict = 37219
ERR_TooLongMetadataName = 37220
ERR_MissingNetModuleReference = 37221
ERR_UnsupportedModule1 = 37222
ERR_UnsupportedEvent1 = 37223
ERR_NetModuleNameMustBeUnique = 37224
ERR_PDBWritingFailed = 37225
ERR_ParamDefaultValueDiffersFromAttribute = 37226
ERR_ResourceInModule = 37227
ERR_FieldHasMultipleDistinctConstantValues = 37228
ERR_AmbiguousInNamespaces2 = 37229
ERR_EncNoPIAReference = 37230
ERR_LinkedNetmoduleMetadataMustProvideFullPEImage = 37231
ERR_CantReadRulesetFile = 37232
ERR_MetadataReferencesNotSupported = 37233
ERR_PlatformDoesntSupport = 37234
ERR_CantUseRequiredAttribute = 37235
ERR_EncodinglessSyntaxTree = 37236
ERR_InvalidFormatSpecifier = 37237
ERR_CannotBeMadeNullable1 = 37238
ERR_BadConditionalWithRef = 37239
ERR_NullPropagatingOpInExpressionTree = 37240
ERR_TooLongOrComplexExpression = 37241
ERR_BadPdbData = 37242
ERR_AutoPropertyCantBeWriteOnly = 37243
ERR_ExpressionDoesntHaveName = 37244
ERR_InvalidNameOfSubExpression = 37245
ERR_MethodTypeArgsUnexpected = 37246
ERR_InReferencedAssembly = 37247
ERR_EncReferenceToAddedMember = 37248
ERR_InterpolationFormatWhitespace = 37249
ERR_InterpolationAlignmentOutOfRange = 37250
ERR_InterpolatedStringFactoryError = 37251
ERR_DebugEntryPointNotSourceMethodDefinition = 37252
ERR_InvalidPathMap = 37253
ERR_PublicSignNoKey = 37254
ERR_TooManyUserStrings = 37255
ERR_PeWritingFailure = 37256
ERR_OptionMustBeAbsolutePath = 37257
ERR_DocFileGen = 37258
ERR_TupleTooFewElements = 37259
ERR_TupleReservedElementNameAnyPosition = 37260
ERR_TupleReservedElementName = 37261
ERR_TupleDuplicateElementName = 37262
ERR_RefReturningCallInExpressionTree = 37263
ERR_SourceLinkRequiresPdb = 37264
ERR_CannotEmbedWithoutPdb = 37265
ERR_InvalidInstrumentationKind = 37266
ERR_ValueTupleTypeRefResolutionError1 = 37267
ERR_TupleElementNamesAttributeMissing = 37268
ERR_ExplicitTupleElementNamesAttribute = 37269
ERR_TupleLiteralDisallowsTypeChar = 37270
ERR_DuplicateProcDefWithDifferentTupleNames2 = 37271
ERR_InterfaceImplementedTwiceWithDifferentTupleNames2 = 37272
ERR_InterfaceImplementedTwiceWithDifferentTupleNames3 = 37273
ERR_InterfaceImplementedTwiceWithDifferentTupleNamesReverse3 = 37274
ERR_InterfaceImplementedTwiceWithDifferentTupleNames4 = 37275
ERR_InterfaceInheritedTwiceWithDifferentTupleNames2 = 37276
ERR_InterfaceInheritedTwiceWithDifferentTupleNames3 = 37277
ERR_InterfaceInheritedTwiceWithDifferentTupleNamesReverse3 = 37278
ERR_InterfaceInheritedTwiceWithDifferentTupleNames4 = 37279
ERR_NewWithTupleTypeSyntax = 37280
ERR_PredefinedValueTupleTypeMustBeStruct = 37281
ERR_PublicSignNetModule = 37282
ERR_BadAssemblyName = 37283
ERR_Merge_conflict_marker_encountered = 37284
ERR_BadSourceCodeKind = 37285
ERR_BadDocumentationMode = 37286
ERR_BadLanguageVersion = 37287
ERR_InvalidPreprocessorConstantType = 37288
ERR_TupleInferredNamesNotAvailable = 37289
ERR_InvalidDebugInfo = 37290
ERR_NoRefOutWhenRefOnly = 37300
ERR_NoNetModuleOutputWhenRefOutOrRefOnly = 37301
ERR_BadNonTrailingNamedArgument = 37302
ERR_ExpectedNamedArgumentInAttributeList = 37303
ERR_NamedArgumentSpecificationBeforeFixedArgumentInLateboundInvocation = 37304
ERR_ValueTupleResolutionAmbiguous3 = 37305
ERR_CommentsAfterLineContinuationNotAvailable1 = 37306
ERR_DefaultInterfaceImplementationInNoPIAType = 37307
ERR_ReAbstractionInNoPIAType = 37308
ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation = 37309
ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember = 37310
ERR_AssignmentInitOnly = 37311
ERR_OverridingInitOnlyProperty = 37312
ERR_PropertyDoesntImplementInitOnly = 37313
'// WARNINGS BEGIN HERE
WRN_UseOfObsoleteSymbol2 = 40000
WRN_InvalidOverrideDueToTupleNames2 = 40001
WRN_MustOverloadBase4 = 40003
WRN_OverrideType5 = 40004
WRN_MustOverride2 = 40005
WRN_DefaultnessShadowed4 = 40007
WRN_UseOfObsoleteSymbolNoMessage1 = 40008
WRN_AssemblyGeneration0 = 40009
WRN_AssemblyGeneration1 = 40010
WRN_ComClassNoMembers1 = 40011
WRN_SynthMemberShadowsMember5 = 40012
WRN_MemberShadowsSynthMember6 = 40014
WRN_SynthMemberShadowsSynthMember7 = 40018
WRN_UseOfObsoletePropertyAccessor3 = 40019
WRN_UseOfObsoletePropertyAccessor2 = 40020
' WRN_MemberShadowsMemberInModule5 = 40021 ' no repro in legacy test, most probably not reachable. Unused in Roslyn.
' WRN_SynthMemberShadowsMemberInModule5 = 40022 ' no repro in legacy test, most probably not reachable. Unused in Roslyn.
' WRN_MemberShadowsSynthMemberInModule6 = 40023 ' no repro in legacy test, most probably not reachable. Unused in Roslyn.
' WRN_SynthMemberShadowsSynthMemberMod7 = 40024 ' no repro in legacy test, most probably not reachable. Unused in Roslyn.
WRN_FieldNotCLSCompliant1 = 40025
WRN_BaseClassNotCLSCompliant2 = 40026
WRN_ProcTypeNotCLSCompliant1 = 40027
WRN_ParamNotCLSCompliant1 = 40028
WRN_InheritedInterfaceNotCLSCompliant2 = 40029
WRN_CLSMemberInNonCLSType3 = 40030
WRN_NameNotCLSCompliant1 = 40031
WRN_EnumUnderlyingTypeNotCLS1 = 40032
WRN_NonCLSMemberInCLSInterface1 = 40033
WRN_NonCLSMustOverrideInCLSType1 = 40034
WRN_ArrayOverloadsNonCLS2 = 40035
WRN_RootNamespaceNotCLSCompliant1 = 40038
WRN_RootNamespaceNotCLSCompliant2 = 40039
WRN_GenericConstraintNotCLSCompliant1 = 40040
WRN_TypeNotCLSCompliant1 = 40041
WRN_OptionalValueNotCLSCompliant1 = 40042
WRN_CLSAttrInvalidOnGetSet = 40043
WRN_TypeConflictButMerged6 = 40046
' WRN_TypeConflictButMerged7 = 40047 ' deprecated
WRN_ShadowingGenericParamWithParam1 = 40048
WRN_CannotFindStandardLibrary1 = 40049
WRN_EventDelegateTypeNotCLSCompliant2 = 40050
WRN_DebuggerHiddenIgnoredOnProperties = 40051
WRN_SelectCaseInvalidRange = 40052
WRN_CLSEventMethodInNonCLSType3 = 40053
WRN_ExpectedInitComponentCall2 = 40054
WRN_NamespaceCaseMismatch3 = 40055
WRN_UndefinedOrEmptyNamespaceOrClass1 = 40056
WRN_UndefinedOrEmptyProjectNamespaceOrClass1 = 40057
'WRN_InterfacesWithNoPIAMustHaveGuid1 = 40058 ' Not reported by Dev11.
WRN_IndirectRefToLinkedAssembly2 = 40059
WRN_DelaySignButNoKey = 40060
WRN_UnimplementedCommandLineSwitch = 40998
' WRN_DuplicateAssemblyAttribute1 = 41000 'unused in Roslyn
WRN_NoNonObsoleteConstructorOnBase3 = 41001
WRN_NoNonObsoleteConstructorOnBase4 = 41002
WRN_RequiredNonObsoleteNewCall3 = 41003
WRN_RequiredNonObsoleteNewCall4 = 41004
WRN_MissingAsClauseinOperator = 41005
WRN_ConstraintsFailedForInferredArgs2 = 41006
WRN_ConditionalNotValidOnFunction = 41007
WRN_UseSwitchInsteadOfAttribute = 41008
WRN_TupleLiteralNameMismatch = 41009
'// AVAILABLE 41010 - 41199
WRN_ReferencedAssemblyDoesNotHaveStrongName = 41997
WRN_RecursiveAddHandlerCall = 41998
WRN_ImplicitConversionCopyBack = 41999
WRN_MustShadowOnMultipleInheritance2 = 42000
' WRN_ObsoleteClassInitialize = 42001 ' deprecated
' WRN_ObsoleteClassTerminate = 42002 ' deprecated
WRN_RecursiveOperatorCall = 42004
' WRN_IndirectlyImplementedBaseMember5 = 42014 ' deprecated
' WRN_ImplementedBaseMember4 = 42015 ' deprecated
WRN_ImplicitConversionSubst1 = 42016 '// populated by 42350/42332/42336/42337/42338/42339/42340
WRN_LateBindingResolution = 42017
WRN_ObjectMath1 = 42018
WRN_ObjectMath2 = 42019
WRN_ObjectAssumedVar1 = 42020 ' // populated by 42111/42346
WRN_ObjectAssumed1 = 42021 ' // populated by 42347/41005/42341/42342/42344/42345/42334/42343
WRN_ObjectAssumedProperty1 = 42022 ' // populated by 42348
'// AVAILABLE 42023
WRN_UnusedLocal = 42024
WRN_SharedMemberThroughInstance = 42025
WRN_RecursivePropertyCall = 42026
WRN_OverlappingCatch = 42029
WRN_DefAsgUseNullRefByRef = 42030
WRN_DuplicateCatch = 42031
WRN_ObjectMath1Not = 42032
WRN_BadChecksumValExtChecksum = 42033
WRN_MultipleDeclFileExtChecksum = 42034
WRN_BadGUIDFormatExtChecksum = 42035
WRN_ObjectMathSelectCase = 42036
WRN_EqualToLiteralNothing = 42037
WRN_NotEqualToLiteralNothing = 42038
'// AVAILABLE 42039 - 42098
WRN_UnusedLocalConst = 42099
'// UNAVAILABLE 42100
WRN_ComClassInterfaceShadows5 = 42101
WRN_ComClassPropertySetObject1 = 42102
'// only reference types are considered for definite assignment.
'// DefAsg's are all under VB_advanced
WRN_DefAsgUseNullRef = 42104
WRN_DefAsgNoRetValFuncRef1 = 42105
WRN_DefAsgNoRetValOpRef1 = 42106
WRN_DefAsgNoRetValPropRef1 = 42107
WRN_DefAsgUseNullRefByRefStr = 42108
WRN_DefAsgUseNullRefStr = 42109
' WRN_FieldInForNotExplicit = 42110 'unused in Roslyn
WRN_StaticLocalNoInference = 42111
'// AVAILABLE 42112 - 42202
' WRN_SxSHigherIndirectRefEmitted4 = 42203 'unused in Roslyn
' WRN_ReferencedAssembliesAmbiguous6 = 42204 'unused in Roslyn
' WRN_ReferencedAssembliesAmbiguous4 = 42205 'unused in Roslyn
' WRN_MaximumNumberOfWarnings = 42206 'unused in Roslyn
WRN_InvalidAssemblyName = 42207
'// AVAILABLE 42209 - 42299
WRN_XMLDocBadXMLLine = 42300
WRN_XMLDocMoreThanOneCommentBlock = 42301
WRN_XMLDocNotFirstOnLine = 42302
WRN_XMLDocInsideMethod = 42303
WRN_XMLDocParseError1 = 42304
WRN_XMLDocDuplicateXMLNode1 = 42305
WRN_XMLDocIllegalTagOnElement2 = 42306
WRN_XMLDocBadParamTag2 = 42307
WRN_XMLDocParamTagWithoutName = 42308
WRN_XMLDocCrefAttributeNotFound1 = 42309
WRN_XMLMissingFileOrPathAttribute1 = 42310
WRN_XMLCannotWriteToXMLDocFile2 = 42311
WRN_XMLDocWithoutLanguageElement = 42312
WRN_XMLDocReturnsOnWriteOnlyProperty = 42313
WRN_XMLDocOnAPartialType = 42314
WRN_XMLDocReturnsOnADeclareSub = 42315
WRN_XMLDocStartTagWithNoEndTag = 42316
WRN_XMLDocBadGenericParamTag2 = 42317
WRN_XMLDocGenericParamTagWithoutName = 42318
WRN_XMLDocExceptionTagWithoutCRef = 42319
WRN_XMLDocInvalidXMLFragment = 42320
WRN_XMLDocBadFormedXML = 42321
WRN_InterfaceConversion2 = 42322
WRN_LiftControlVariableLambda = 42324
' 42325 unused, was abandoned, now used in unit test "EnsureLegacyWarningsAreMaintained". Please update test if you are going to use this number.
WRN_LambdaPassedToRemoveHandler = 42326
WRN_LiftControlVariableQuery = 42327
WRN_RelDelegatePassedToRemoveHandler = 42328
' WRN_QueryMissingAsClauseinVarDecl = 42329 ' unused in Roslyn.
' WRN_LiftUsingVariableInLambda1 = 42330 ' unused in Roslyn.
' WRN_LiftUsingVariableInQuery1 = 42331 ' unused in Roslyn.
WRN_AmbiguousCastConversion2 = 42332 '// substitutes into 42016
WRN_VarianceDeclarationAmbiguous3 = 42333
WRN_ArrayInitNoTypeObjectAssumed = 42334
WRN_TypeInferenceAssumed3 = 42335
WRN_VarianceConversionFailedOut6 = 42336 '// substitutes into 42016
WRN_VarianceConversionFailedIn6 = 42337 '// substitutes into 42016
WRN_VarianceIEnumerableSuggestion3 = 42338 '// substitutes into 42016
WRN_VarianceConversionFailedTryOut4 = 42339 '// substitutes into 42016
WRN_VarianceConversionFailedTryIn4 = 42340 '// substitutes into 42016
WRN_IfNoTypeObjectAssumed = 42341
WRN_IfTooManyTypesObjectAssumed = 42342
WRN_ArrayInitTooManyTypesObjectAssumed = 42343
WRN_LambdaNoTypeObjectAssumed = 42344
WRN_LambdaTooManyTypesObjectAssumed = 42345
WRN_MissingAsClauseinVarDecl = 42346
WRN_MissingAsClauseinFunction = 42347
WRN_MissingAsClauseinProperty = 42348
WRN_ObsoleteIdentityDirectCastForValueType = 42349
WRN_ImplicitConversion2 = 42350 ' // substitutes into 42016
WRN_MutableStructureInUsing = 42351
WRN_MutableGenericStructureInUsing = 42352
WRN_DefAsgNoRetValFuncVal1 = 42353
WRN_DefAsgNoRetValOpVal1 = 42354
WRN_DefAsgNoRetValPropVal1 = 42355
WRN_AsyncLacksAwaits = 42356
WRN_AsyncSubCouldBeFunction = 42357
WRN_UnobservedAwaitableExpression = 42358
WRN_UnobservedAwaitableDelegate = 42359
WRN_PrefixAndXmlnsLocalName = 42360
WRN_UseValueForXmlExpression3 = 42361 ' Replaces ERR_UseValueForXmlExpression3
'WRN_PDBConstantStringValueTooLong = 42363 we gave up on this warning. See comments in commonCompilation.Emit()
WRN_ReturnTypeAttributeOnWriteOnlyProperty = 42364
ERR_UnmanagedCallersOnlyNotSupported = 42365
WRN_InvalidVersionFormat = 42366
WRN_MainIgnored = 42367
WRN_EmptyPrefixAndXmlnsLocalName = 42368
WRN_DefAsgNoRetValWinRtEventVal1 = 42369
WRN_AssemblyAttributeFromModuleIsOverridden = 42370
WRN_RefCultureMismatch = 42371
WRN_ConflictingMachineAssembly = 42372
WRN_PdbLocalNameTooLong = 42373
WRN_PdbUsingNameTooLong = 42374
WRN_XMLDocCrefToTypeParameter = 42375
WRN_AnalyzerCannotBeCreated = 42376
WRN_NoAnalyzerInAssembly = 42377
WRN_UnableToLoadAnalyzer = 42378
WRN_AttributeIgnoredWhenPublicSigning = 42379
WRN_Experimental = 42380
WRN_AttributeNotSupportedInVB = 42381
ERR_MultipleAnalyzerConfigsInSameDir = 42500
WRN_GeneratorFailedDuringInitialization = 42501
WRN_GeneratorFailedDuringGeneration = 42502
WRN_AnalyzerReferencesFramework = 42503
WRN_CallerArgumentExpressionAttributeSelfReferential = 42504
WRN_CallerArgumentExpressionAttributeHasInvalidParameterName = 42505
' // AVAILABLE 42600 - 49998
ERRWRN_NextAvailable = 42600
'// HIDDENS AND INFOS BEGIN HERE
HDN_UnusedImportClause = 50000
HDN_UnusedImportStatement = 50001
INF_UnableToLoadSomeTypesInAnalyzer = 50002
' // AVAILABLE 50003 - 54999
' Adding diagnostic arguments from resx file
IDS_ProjectSettingsLocationName = 56000
IDS_FunctionReturnType = 56001
IDS_TheSystemCannotFindThePathSpecified = 56002
' available: 56003
IDS_MSG_ADDMODULE = 56004
IDS_MSG_ADDLINKREFERENCE = 56005
IDS_MSG_ADDREFERENCE = 56006
IDS_LogoLine1 = 56007
IDS_LogoLine2 = 56008
IDS_VBCHelp = 56009
IDS_LangVersions = 56010
IDS_ToolName = 56011
ERR_StdInOptionProvidedButConsoleInputIsNotRedirected = 56032
' Feature codes
FEATURE_AutoProperties
FEATURE_LineContinuation
FEATURE_StatementLambdas
FEATURE_CoContraVariance
FEATURE_CollectionInitializers
FEATURE_SubLambdas
FEATURE_ArrayLiterals
FEATURE_AsyncExpressions
FEATURE_Iterators
FEATURE_GlobalNamespace
FEATURE_NullPropagatingOperator
FEATURE_NameOfExpressions
FEATURE_ReadonlyAutoProperties
FEATURE_RegionsEverywhere
FEATURE_MultilineStringLiterals
FEATURE_CObjInAttributeArguments
FEATURE_LineContinuationComments
FEATURE_TypeOfIsNot
FEATURE_YearFirstDateLiterals
FEATURE_WarningDirectives
FEATURE_PartialModules
FEATURE_PartialInterfaces
FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite
FEATURE_DigitSeparators
FEATURE_BinaryLiterals
FEATURE_Tuples
FEATURE_LeadingDigitSeparator
FEATURE_PrivateProtected
FEATURE_InterpolatedStrings
FEATURE_UnconstrainedTypeParameterInConditional
FEATURE_CommentsAfterLineContinuation
FEATURE_InitOnlySettersUsage
FEATURE_CallerArgumentExpression
End Enum
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.
'//-------------------------------------------------------------------------------------------------
'//
'// Error code and strings for Compiler errors
'//
'// ERRIDs should be defined in the following ranges:
'//
'// 500 - 999 - non localized ERRID (main DLL)
'// 30000 - 59999 - localized ERRID (intl DLL)
'//
'// The convention for naming ERRID's that take replacement strings is to give
'// them a number following the name (from 1-9) that indicates how many
'// arguments they expect.
'//
'// DO NOT USE ANY NUMBERS EXCEPT THOSE EXPLICITLY LISTED AS BEING AVAILABLE.
'// IF YOU REUSE A NUMBER, LOCALIZATION WILL BE SCREWED UP!
'//
'//-------------------------------------------------------------------------------------------------
' //-------------------------------------------------------------------------------------------------
' //
' //
' // Manages the parse and compile errors.
' //
' //-------------------------------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Enum ERRID
Void = InternalErrorCode.Void
Unknown = InternalErrorCode.Unknown
ERR_None = 0
' ERR_InitError = 2000 unused in Roslyn
ERR_FileNotFound = 2001
' WRN_FileAlreadyIncluded = 2002 'unused in Roslyn.
'ERR_DuplicateResponseFile = 2003 unused in Roslyn.
'ERR_NoMemory = 2004
ERR_ArgumentRequired = 2006
WRN_BadSwitch = 2007
ERR_NoSources = 2008
ERR_SwitchNeedsBool = 2009
'ERR_CompileFailed = 2010 unused in Roslyn.
ERR_NoResponseFile = 2011
ERR_CantOpenFileWrite = 2012
ERR_InvalidSwitchValue = 2014
ERR_BinaryFile = 2015
ERR_BadCodepage = 2016
ERR_LibNotFound = 2017
'ERR_MaximumErrors = 2020 unused in Roslyn.
ERR_IconFileAndWin32ResFile = 2023
'WRN_ReservedReference = 2024 ' unused by native compiler due to bug.
WRN_NoConfigInResponseFile = 2025
' WRN_InvalidWarningId = 2026 ' unused in Roslyn.
'ERR_WatsonSendNotOptedIn = 2027
' WRN_SwitchNoBool = 2028 'unused in Roslyn
ERR_NoSourcesOut = 2029
ERR_NeedModule = 2030
ERR_InvalidAssemblyName = 2031
FTL_InvalidInputFileName = 2032 ' new in Roslyn
ERR_ConflictingManifestSwitches = 2033
WRN_IgnoreModuleManifest = 2034
'ERR_NoDefaultManifest = 2035
'ERR_InvalidSwitchValue1 = 2036
WRN_BadUILang = 2038 ' new in Roslyn
ERR_VBCoreNetModuleConflict = 2042
ERR_InvalidFormatForGuidForOption = 2043
ERR_MissingGuidForOption = 2044
ERR_BadChecksumAlgorithm = 2045
ERR_MutuallyExclusiveOptions = 2046
ERR_BadSwitchValue = 2047
'// The naming convention is that if your error requires arguments, to append
'// the number of args taken, e.g. AmbiguousName2
'//
ERR_InvalidInNamespace = 30001
ERR_UndefinedType1 = 30002
ERR_MissingNext = 30003
ERR_IllegalCharConstant = 30004
'//If you make any change involving these errors, such as creating more specific versions for use
'//in other contexts, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
ERR_UnreferencedAssemblyEvent3 = 30005
ERR_UnreferencedModuleEvent3 = 30006
' ERR_UnreferencedAssemblyBase3 = 30007
' ERR_UnreferencedModuleBase3 = 30008 - This has been superceded by ERR_UnreferencedModuleEvent3
' ERR_UnreferencedAssemblyImplements3 = 30009
'ERR_UnreferencedModuleImplements3 = 30010 - This has been superceded by ERR_UnreferencedModuleEvent3
'ERR_CodegenError = 30011
ERR_LbExpectedEndIf = 30012
ERR_LbNoMatchingIf = 30013
ERR_LbBadElseif = 30014
ERR_InheritsFromRestrictedType1 = 30015
ERR_InvOutsideProc = 30016
ERR_DelegateCantImplement = 30018
ERR_DelegateCantHandleEvents = 30019
ERR_IsOperatorRequiresReferenceTypes1 = 30020
ERR_TypeOfRequiresReferenceType1 = 30021
ERR_ReadOnlyHasSet = 30022
ERR_WriteOnlyHasGet = 30023
ERR_InvInsideProc = 30024
ERR_EndProp = 30025
ERR_EndSubExpected = 30026
ERR_EndFunctionExpected = 30027
ERR_LbElseNoMatchingIf = 30028
ERR_CantRaiseBaseEvent = 30029
ERR_TryWithoutCatchOrFinally = 30030
' ERR_FullyQualifiedNameTooLong1 = 30031 ' Deprecated in favor of ERR_TooLongMetadataName
ERR_EventsCantBeFunctions = 30032
' ERR_IdTooLong = 30033 ' Deprecated in favor of ERR_TooLongMetadataName
ERR_MissingEndBrack = 30034
ERR_Syntax = 30035
ERR_Overflow = 30036
ERR_IllegalChar = 30037
ERR_StrictDisallowsObjectOperand1 = 30038
ERR_LoopControlMustNotBeProperty = 30039
ERR_MethodBodyNotAtLineStart = 30040
ERR_MaximumNumberOfErrors = 30041
ERR_UseOfKeywordNotInInstanceMethod1 = 30043
ERR_UseOfKeywordFromStructure1 = 30044
ERR_BadAttributeConstructor1 = 30045
ERR_ParamArrayWithOptArgs = 30046
ERR_ExpectedArray1 = 30049
ERR_ParamArrayNotArray = 30050
ERR_ParamArrayRank = 30051
ERR_ArrayRankLimit = 30052
ERR_AsNewArray = 30053
ERR_TooManyArgs1 = 30057
ERR_ExpectedCase = 30058
ERR_RequiredConstExpr = 30059
ERR_RequiredConstConversion2 = 30060
ERR_InvalidMe = 30062
ERR_ReadOnlyAssignment = 30064
ERR_ExitSubOfFunc = 30065
ERR_ExitPropNot = 30066
ERR_ExitFuncOfSub = 30067
ERR_LValueRequired = 30068
ERR_ForIndexInUse1 = 30069
ERR_NextForMismatch1 = 30070
ERR_CaseElseNoSelect = 30071
ERR_CaseNoSelect = 30072
ERR_CantAssignToConst = 30074
ERR_NamedSubscript = 30075
ERR_ExpectedEndIf = 30081
ERR_ExpectedEndWhile = 30082
ERR_ExpectedLoop = 30083
ERR_ExpectedNext = 30084
ERR_ExpectedEndWith = 30085
ERR_ElseNoMatchingIf = 30086
ERR_EndIfNoMatchingIf = 30087
ERR_EndSelectNoSelect = 30088
ERR_ExitDoNotWithinDo = 30089
ERR_EndWhileNoWhile = 30090
ERR_LoopNoMatchingDo = 30091
ERR_NextNoMatchingFor = 30092
ERR_EndWithWithoutWith = 30093
ERR_MultiplyDefined1 = 30094
ERR_ExpectedEndSelect = 30095
ERR_ExitForNotWithinFor = 30096
ERR_ExitWhileNotWithinWhile = 30097
ERR_ReadOnlyProperty1 = 30098
ERR_ExitSelectNotWithinSelect = 30099
ERR_BranchOutOfFinally = 30101
ERR_QualNotObjectRecord1 = 30103
ERR_TooFewIndices = 30105
ERR_TooManyIndices = 30106
ERR_EnumNotExpression1 = 30107
ERR_TypeNotExpression1 = 30108
ERR_ClassNotExpression1 = 30109
ERR_StructureNotExpression1 = 30110
ERR_InterfaceNotExpression1 = 30111
ERR_NamespaceNotExpression1 = 30112
ERR_BadNamespaceName1 = 30113
ERR_XmlPrefixNotExpression = 30114
ERR_MultipleExtends = 30121
'ERR_NoStopInDebugger = 30122
'ERR_NoEndInDebugger = 30123
ERR_PropMustHaveGetSet = 30124
ERR_WriteOnlyHasNoWrite = 30125
ERR_ReadOnlyHasNoGet = 30126
ERR_BadAttribute1 = 30127
' ERR_BadSecurityAttribute1 = 30128 ' we're now reporting more detailed diagnostics: ERR_SecurityAttributeMissingAction or ERR_SecurityAttributeInvalidAction
'ERR_BadAssemblyAttribute1 = 30129
'ERR_BadModuleAttribute1 = 30130
' ERR_ModuleSecurityAttributeNotAllowed1 = 30131 ' We now report ERR_SecurityAttributeInvalidTarget instead.
ERR_LabelNotDefined1 = 30132
'ERR_NoGotosInDebugger = 30133
'ERR_NoLabelsInDebugger = 30134
'ERR_NoSyncLocksInDebugger = 30135
ERR_ErrorCreatingWin32ResourceFile = 30136
'ERR_ErrorSavingWin32ResourceFile = 30137 abandoned. no longer "saving" a temporary resource file.
ERR_UnableToCreateTempFile = 30138 'changed from ERR_UnableToCreateTempFileInPath1. now takes only one argument
'ERR_ErrorSettingManifestOption = 30139
'ERR_ErrorCreatingManifest = 30140
'ERR_UnableToCreateALinkAPI = 30141
'ERR_UnableToGenerateRefToMetaDataFile1 = 30142
'ERR_UnableToEmbedResourceFile1 = 30143 ' We now report ERR_UnableToOpenResourceFile1 instead.
'ERR_UnableToLinkResourceFile1 = 30144 ' We now report ERR_UnableToOpenResourceFile1 instead.
'ERR_UnableToEmitAssembly = 30145
'ERR_UnableToSignAssembly = 30146
'ERR_NoReturnsInDebugger = 30147
ERR_RequiredNewCall2 = 30148
ERR_UnimplementedMember3 = 30149
' ERR_UnimplementedProperty3 = 30154
ERR_BadWithRef = 30157
' ERR_ExpectedNewableClass1 = 30166 unused in Roslyn. We now report nothing
' ERR_TypeConflict7 = 30175 unused in Roslyn. We now report BC30179
ERR_DuplicateAccessCategoryUsed = 30176
ERR_DuplicateModifierCategoryUsed = 30177
ERR_DuplicateSpecifier = 30178
ERR_TypeConflict6 = 30179
ERR_UnrecognizedTypeKeyword = 30180
ERR_ExtraSpecifiers = 30181
ERR_UnrecognizedType = 30182
ERR_InvalidUseOfKeyword = 30183
ERR_InvalidEndEnum = 30184
ERR_MissingEndEnum = 30185
'ERR_NoUsingInDebugger = 30186
ERR_ExpectedDeclaration = 30188
ERR_ParamArrayMustBeLast = 30192
ERR_SpecifiersInvalidOnInheritsImplOpt = 30193
ERR_ExpectedSpecifier = 30195
ERR_ExpectedComma = 30196
ERR_ExpectedAs = 30197
ERR_ExpectedRparen = 30198
ERR_ExpectedLparen = 30199
ERR_InvalidNewInType = 30200
ERR_ExpectedExpression = 30201
ERR_ExpectedOptional = 30202
ERR_ExpectedIdentifier = 30203
ERR_ExpectedIntLiteral = 30204
ERR_ExpectedEOS = 30205
ERR_ExpectedForOptionStmt = 30206
ERR_InvalidOptionCompare = 30207
ERR_ExpectedOptionCompare = 30208
ERR_StrictDisallowImplicitObject = 30209
ERR_StrictDisallowsImplicitProc = 30210
ERR_StrictDisallowsImplicitArgs = 30211
ERR_InvalidParameterSyntax = 30213
ERR_ExpectedSubFunction = 30215
ERR_ExpectedStringLiteral = 30217
ERR_MissingLibInDeclare = 30218
ERR_DelegateNoInvoke1 = 30220
ERR_MissingIsInTypeOf = 30224
ERR_DuplicateOption1 = 30225
ERR_ModuleCantInherit = 30230
ERR_ModuleCantImplement = 30231
ERR_BadImplementsType = 30232
ERR_BadConstFlags1 = 30233
ERR_BadWithEventsFlags1 = 30234
ERR_BadDimFlags1 = 30235
ERR_DuplicateParamName1 = 30237
ERR_LoopDoubleCondition = 30238
ERR_ExpectedRelational = 30239
ERR_ExpectedExitKind = 30240
ERR_ExpectedNamedArgument = 30241
ERR_BadMethodFlags1 = 30242
ERR_BadEventFlags1 = 30243
ERR_BadDeclareFlags1 = 30244
ERR_BadLocalConstFlags1 = 30246
ERR_BadLocalDimFlags1 = 30247
ERR_ExpectedConditionalDirective = 30248
ERR_ExpectedEQ = 30249
ERR_ConstructorNotFound1 = 30251
ERR_InvalidEndInterface = 30252
ERR_MissingEndInterface = 30253
ERR_InheritsFrom2 = 30256
ERR_InheritanceCycle1 = 30257
ERR_InheritsFromNonClass = 30258
ERR_MultiplyDefinedType3 = 30260
ERR_BadOverrideAccess2 = 30266
ERR_CantOverrideNotOverridable2 = 30267
ERR_DuplicateProcDef1 = 30269
ERR_BadInterfaceMethodFlags1 = 30270
ERR_NamedParamNotFound2 = 30272
ERR_BadInterfacePropertyFlags1 = 30273
ERR_NamedArgUsedTwice2 = 30274
ERR_InterfaceCantUseEventSpecifier1 = 30275
ERR_TypecharNoMatch2 = 30277
ERR_ExpectedSubOrFunction = 30278
ERR_BadEmptyEnum1 = 30280
ERR_InvalidConstructorCall = 30282
ERR_CantOverrideConstructor = 30283
ERR_OverrideNotNeeded3 = 30284
ERR_ExpectedDot = 30287
ERR_DuplicateLocals1 = 30288
ERR_InvInsideEndsProc = 30289
ERR_LocalSameAsFunc = 30290
ERR_RecordEmbeds2 = 30293
ERR_RecordCycle2 = 30294
ERR_InterfaceCycle1 = 30296
ERR_SubNewCycle2 = 30297
ERR_SubNewCycle1 = 30298
ERR_InheritsFromCantInherit3 = 30299
ERR_OverloadWithOptional2 = 30300
ERR_OverloadWithReturnType2 = 30301
ERR_TypeCharWithType1 = 30302
ERR_TypeCharOnSub = 30303
ERR_OverloadWithDefault2 = 30305
ERR_MissingSubscript = 30306
ERR_OverrideWithDefault2 = 30307
ERR_OverrideWithOptional2 = 30308
ERR_FieldOfValueFieldOfMarshalByRef3 = 30310
ERR_TypeMismatch2 = 30311
ERR_CaseAfterCaseElse = 30321
ERR_ConvertArrayMismatch4 = 30332
ERR_ConvertObjectArrayMismatch3 = 30333
ERR_ForLoopType1 = 30337
ERR_OverloadWithByref2 = 30345
ERR_InheritsFromNonInterface = 30354
ERR_BadInterfaceOrderOnInherits = 30357
ERR_DuplicateDefaultProps1 = 30359
ERR_DefaultMissingFromProperty2 = 30361
ERR_OverridingPropertyKind2 = 30362
ERR_NewInInterface = 30363
ERR_BadFlagsOnNew1 = 30364
ERR_OverloadingPropertyKind2 = 30366
ERR_NoDefaultNotExtend1 = 30367
ERR_OverloadWithArrayVsParamArray2 = 30368
ERR_BadInstanceMemberAccess = 30369
ERR_ExpectedRbrace = 30370
ERR_ModuleAsType1 = 30371
ERR_NewIfNullOnNonClass = 30375
'ERR_NewIfNullOnAbstractClass1 = 30376
ERR_CatchAfterFinally = 30379
ERR_CatchNoMatchingTry = 30380
ERR_FinallyAfterFinally = 30381
ERR_FinallyNoMatchingTry = 30382
ERR_EndTryNoTry = 30383
ERR_ExpectedEndTry = 30384
ERR_BadDelegateFlags1 = 30385
ERR_NoConstructorOnBase2 = 30387
ERR_InaccessibleSymbol2 = 30389
ERR_InaccessibleMember3 = 30390
ERR_CatchNotException1 = 30392
ERR_ExitTryNotWithinTry = 30393
ERR_BadRecordFlags1 = 30395
ERR_BadEnumFlags1 = 30396
ERR_BadInterfaceFlags1 = 30397
ERR_OverrideWithByref2 = 30398
ERR_MyBaseAbstractCall1 = 30399
ERR_IdentNotMemberOfInterface4 = 30401
ERR_ImplementingInterfaceWithDifferentTupleNames5 = 30402
'//We intentionally use argument '3' for the delegate name. This makes generating overload resolution errors
'//easy. To make it more clear that were doing this, we name the message DelegateBindingMismatch3_2.
'//This differentiates its from DelegateBindingMismatch3_3, which actually takes 3 parameters instead of 2.
'//This is a workaround, but it makes the logic for reporting overload resolution errors easier error report more straight forward.
'ERR_DelegateBindingMismatch3_2 = 30408
ERR_WithEventsRequiresClass = 30412
ERR_WithEventsAsStruct = 30413
ERR_ConvertArrayRankMismatch2 = 30414
ERR_RedimRankMismatch = 30415
ERR_StartupCodeNotFound1 = 30420
ERR_ConstAsNonConstant = 30424
ERR_InvalidEndSub = 30429
ERR_InvalidEndFunction = 30430
ERR_InvalidEndProperty = 30431
ERR_ModuleCantUseMethodSpecifier1 = 30433
ERR_ModuleCantUseEventSpecifier1 = 30434
ERR_StructCantUseVarSpecifier1 = 30435
'ERR_ModuleCantUseMemberSpecifier1 = 30436 Now reporting BC30735
ERR_InvalidOverrideDueToReturn2 = 30437
ERR_ConstantWithNoValue = 30438
ERR_ExpressionOverflow1 = 30439
'ERR_ExpectedEndTryCatch = 30441 - No Longer Reported. Removed per bug 926779
'ERR_ExpectedEndTryFinally = 30442 - No Longer Reported. Removed per bug 926779
ERR_DuplicatePropertyGet = 30443
ERR_DuplicatePropertySet = 30444
' ERR_ConstAggregate = 30445 Now giving BC30424
ERR_NameNotDeclared1 = 30451
ERR_BinaryOperands3 = 30452
ERR_ExpectedProcedure = 30454
ERR_OmittedArgument2 = 30455
ERR_NameNotMember2 = 30456
'ERR_NoTypeNamesAvailable = 30458
ERR_EndClassNoClass = 30460
ERR_BadClassFlags1 = 30461
ERR_ImportsMustBeFirst = 30465
ERR_NonNamespaceOrClassOnImport2 = 30467
ERR_TypecharNotallowed = 30468
ERR_ObjectReferenceNotSupplied = 30469
ERR_MyClassNotInClass = 30470
ERR_IndexedNotArrayOrProc = 30471
ERR_EventSourceIsArray = 30476
ERR_SharedConstructorWithParams = 30479
ERR_SharedConstructorIllegalSpec1 = 30480
ERR_ExpectedEndClass = 30481
ERR_UnaryOperand2 = 30487
ERR_BadFlagsWithDefault1 = 30490
ERR_VoidValue = 30491
ERR_ConstructorFunction = 30493
'ERR_LineTooLong = 30494 - No longer reported. Removed per 926916
ERR_InvalidLiteralExponent = 30495
ERR_NewCannotHandleEvents = 30497
ERR_CircularEvaluation1 = 30500
ERR_BadFlagsOnSharedMeth1 = 30501
ERR_BadFlagsOnSharedProperty1 = 30502
ERR_BadFlagsOnStdModuleProperty1 = 30503
ERR_SharedOnProcThatImpl = 30505
ERR_NoWithEventsVarOnHandlesList = 30506
ERR_AccessMismatch6 = 30508
ERR_InheritanceAccessMismatch5 = 30509
ERR_NarrowingConversionDisallowed2 = 30512
ERR_NoArgumentCountOverloadCandidates1 = 30516
ERR_NoViableOverloadCandidates1 = 30517
ERR_NoCallableOverloadCandidates2 = 30518
ERR_NoNonNarrowingOverloadCandidates2 = 30519
ERR_ArgumentNarrowing3 = 30520
ERR_NoMostSpecificOverload2 = 30521
ERR_NotMostSpecificOverload = 30522
ERR_OverloadCandidate2 = 30523
ERR_NoGetProperty1 = 30524
ERR_NoSetProperty1 = 30526
'ERR_ArrayType2 = 30528
ERR_ParamTypingInconsistency = 30529
ERR_ParamNameFunctionNameCollision = 30530
ERR_DateToDoubleConversion = 30532
ERR_DoubleToDateConversion = 30533
ERR_ZeroDivide = 30542
ERR_TryAndOnErrorDoNotMix = 30544
ERR_PropertyAccessIgnored = 30545
ERR_InterfaceNoDefault1 = 30547
ERR_InvalidAssemblyAttribute1 = 30548
ERR_InvalidModuleAttribute1 = 30549
ERR_AmbiguousInUnnamedNamespace1 = 30554
ERR_DefaultMemberNotProperty1 = 30555
ERR_AmbiguousInNamespace2 = 30560
ERR_AmbiguousInImports2 = 30561
ERR_AmbiguousInModules2 = 30562
' ERR_AmbiguousInApplicationObject2 = 30563 ' comment out in Dev10
ERR_ArrayInitializerTooFewDimensions = 30565
ERR_ArrayInitializerTooManyDimensions = 30566
ERR_InitializerTooFewElements1 = 30567
ERR_InitializerTooManyElements1 = 30568
ERR_NewOnAbstractClass = 30569
ERR_DuplicateNamedImportAlias1 = 30572
ERR_DuplicatePrefix = 30573
ERR_StrictDisallowsLateBinding = 30574
' ERR_PropertyMemberSyntax = 30576 unused in Roslyn
ERR_AddressOfOperandNotMethod = 30577
ERR_EndExternalSource = 30578
ERR_ExpectedEndExternalSource = 30579
ERR_NestedExternalSource = 30580
ERR_AddressOfNotDelegate1 = 30581
ERR_SyncLockRequiresReferenceType1 = 30582
ERR_MethodAlreadyImplemented2 = 30583
ERR_DuplicateInInherits1 = 30584
ERR_NamedParamArrayArgument = 30587
ERR_OmittedParamArrayArgument = 30588
ERR_ParamArrayArgumentMismatch = 30589
ERR_EventNotFound1 = 30590
'ERR_NoDefaultSource = 30591
ERR_ModuleCantUseVariableSpecifier1 = 30593
ERR_SharedEventNeedsSharedHandler = 30594
ERR_ExpectedMinus = 30601
ERR_InterfaceMemberSyntax = 30602
ERR_InvInsideInterface = 30603
ERR_InvInsideEndsInterface = 30604
ERR_BadFlagsInNotInheritableClass1 = 30607
ERR_UnimplementedMustOverride = 30609 ' substituted into ERR_BaseOnlyClassesMustBeExplicit2
ERR_BaseOnlyClassesMustBeExplicit2 = 30610
ERR_NegativeArraySize = 30611
ERR_MyClassAbstractCall1 = 30614
ERR_EndDisallowedInDllProjects = 30615
ERR_BlockLocalShadowing1 = 30616
ERR_ModuleNotAtNamespace = 30617
ERR_NamespaceNotAtNamespace = 30618
ERR_InvInsideEndsEnum = 30619
ERR_InvalidOptionStrict = 30620
ERR_EndStructureNoStructure = 30621
ERR_EndModuleNoModule = 30622
ERR_EndNamespaceNoNamespace = 30623
ERR_ExpectedEndStructure = 30624
ERR_ExpectedEndModule = 30625
ERR_ExpectedEndNamespace = 30626
ERR_OptionStmtWrongOrder = 30627
ERR_StructCantInherit = 30628
ERR_NewInStruct = 30629
ERR_InvalidEndGet = 30630
ERR_MissingEndGet = 30631
ERR_InvalidEndSet = 30632
ERR_MissingEndSet = 30633
ERR_InvInsideEndsProperty = 30634
ERR_DuplicateWriteabilityCategoryUsed = 30635
ERR_ExpectedGreater = 30636
ERR_AttributeStmtWrongOrder = 30637
ERR_NoExplicitArraySizes = 30638
ERR_BadPropertyFlags1 = 30639
ERR_InvalidOptionExplicit = 30640
ERR_MultipleParameterSpecifiers = 30641
ERR_MultipleOptionalParameterSpecifiers = 30642
ERR_UnsupportedProperty1 = 30643
ERR_InvalidOptionalParameterUsage1 = 30645
ERR_ReturnFromNonFunction = 30647
ERR_UnterminatedStringLiteral = 30648
ERR_UnsupportedType1 = 30649
ERR_InvalidEnumBase = 30650
ERR_ByRefIllegal1 = 30651
'//If you make any change involving these errors, such as creating more specific versions for use
'//in other contexts, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
ERR_UnreferencedAssembly3 = 30652
ERR_UnreferencedModule3 = 30653
ERR_ReturnWithoutValue = 30654
' ERR_CantLoadStdLibrary1 = 30655 roslyn doesn't use special messages when well-known assemblies cannot be loaded.
ERR_UnsupportedField1 = 30656
ERR_UnsupportedMethod1 = 30657
ERR_NoNonIndexProperty1 = 30658
ERR_BadAttributePropertyType1 = 30659
ERR_LocalsCannotHaveAttributes = 30660
ERR_PropertyOrFieldNotDefined1 = 30661
ERR_InvalidAttributeUsage2 = 30662
ERR_InvalidMultipleAttributeUsage1 = 30663
ERR_CantThrowNonException = 30665
ERR_MustBeInCatchToRethrow = 30666
ERR_ParamArrayMustBeByVal = 30667
ERR_UseOfObsoleteSymbol2 = 30668
ERR_RedimNoSizes = 30670
ERR_InitWithMultipleDeclarators = 30671
ERR_InitWithExplicitArraySizes = 30672
ERR_EndSyncLockNoSyncLock = 30674
ERR_ExpectedEndSyncLock = 30675
ERR_NameNotEvent2 = 30676
ERR_AddOrRemoveHandlerEvent = 30677
ERR_UnrecognizedEnd = 30678
ERR_ArrayInitForNonArray2 = 30679
ERR_EndRegionNoRegion = 30680
ERR_ExpectedEndRegion = 30681
ERR_InheritsStmtWrongOrder = 30683
ERR_AmbiguousAcrossInterfaces3 = 30685
ERR_DefaultPropertyAmbiguousAcrossInterfaces4 = 30686
ERR_InterfaceEventCantUse1 = 30688
ERR_ExecutableAsDeclaration = 30689
ERR_StructureNoDefault1 = 30690
' ERR_TypeMemberAsExpression2 = 30691 Now giving BC30109
ERR_MustShadow2 = 30695
'ERR_OverloadWithOptionalTypes2 = 30696
ERR_OverrideWithOptionalTypes2 = 30697
'ERR_UnableToGetTempPath = 30698
'ERR_NameNotDeclaredDebug1 = 30699
'// This error should never be seen.
'ERR_NoSideEffects = 30700
'ERR_InvalidNothing = 30701
'ERR_IndexOutOfRange1 = 30702
'ERR_RuntimeException2 = 30703
'ERR_RuntimeException = 30704
'ERR_ObjectReferenceIsNothing1 = 30705
'// This error should never be seen.
'ERR_ExpressionNotValidInEE = 30706
'ERR_UnableToEvaluateExpression = 30707
'ERR_UnableToEvaluateLoops = 30708
'ERR_NoDimsInDebugger = 30709
ERR_ExpectedEndOfExpression = 30710
'ERR_SetValueNotAllowedOnNonLeafFrame = 30711
'ERR_UnableToClassInformation1 = 30712
'ERR_NoExitInDebugger = 30713
'ERR_NoResumeInDebugger = 30714
'ERR_NoCatchInDebugger = 30715
'ERR_NoFinallyInDebugger = 30716
'ERR_NoTryInDebugger = 30717
'ERR_NoSelectInDebugger = 30718
'ERR_NoCaseInDebugger = 30719
'ERR_NoOnErrorInDebugger = 30720
'ERR_EvaluationAborted = 30721
'ERR_EvaluationTimeout = 30722
'ERR_EvaluationNoReturnValue = 30723
'ERR_NoErrorStatementInDebugger = 30724
'ERR_NoThrowStatementInDebugger = 30725
'ERR_NoWithContextInDebugger = 30726
ERR_StructsCannotHandleEvents = 30728
ERR_OverridesImpliesOverridable = 30730
'ERR_NoAddressOfInDebugger = 30731
'ERR_EvaluationOfWebMethods = 30732
ERR_LocalNamedSameAsParam1 = 30734
ERR_ModuleCantUseTypeSpecifier1 = 30735
'ERR_EvaluationBadStartPoint = 30736
ERR_InValidSubMainsFound1 = 30737
ERR_MoreThanOneValidMainWasFound2 = 30738
'ERR_NoRaiseEventOfInDebugger = 30739
'ERR_InvalidCast2 = 30741
ERR_CannotConvertValue2 = 30742
'ERR_ArrayElementIsNothing = 30744
'ERR_InternalCompilerError = 30747
'ERR_InvalidCast1 = 30748
'ERR_UnableToGetValue = 30749
'ERR_UnableToLoadType1 = 30750
'ERR_UnableToGetTypeInformationFor1 = 30751
ERR_OnErrorInSyncLock = 30752
ERR_NarrowingConversionCollection2 = 30753
ERR_GotoIntoTryHandler = 30754
ERR_GotoIntoSyncLock = 30755
ERR_GotoIntoWith = 30756
ERR_GotoIntoFor = 30757
ERR_BadAttributeNonPublicConstructor = 30758
'ERR_ArrayElementIsNothing1 = 30759
'ERR_ObjectReferenceIsNothing = 30760
' ERR_StarliteDisallowsLateBinding = 30762
' ERR_StarliteBadDeclareFlags = 30763
' ERR_NoStarliteOverloadResolution = 30764
'ERR_NoSupportFileIOKeywords1 = 30766
' ERR_NoSupportGetStatement = 30767 - starlite error message
' ERR_NoSupportLineKeyword = 30768 cut from Roslyn
' ERR_StarliteDisallowsEndStatement = 30769 cut from Roslyn
ERR_DefaultEventNotFound1 = 30770
ERR_InvalidNonSerializedUsage = 30772
'ERR_NoContinueInDebugger = 30780
ERR_ExpectedContinueKind = 30781
ERR_ContinueDoNotWithinDo = 30782
ERR_ContinueForNotWithinFor = 30783
ERR_ContinueWhileNotWithinWhile = 30784
ERR_DuplicateParameterSpecifier = 30785
ERR_ModuleCantUseDLLDeclareSpecifier1 = 30786
ERR_StructCantUseDLLDeclareSpecifier1 = 30791
ERR_TryCastOfValueType1 = 30792
ERR_TryCastOfUnconstrainedTypeParam1 = 30793
ERR_AmbiguousDelegateBinding2 = 30794
ERR_SharedStructMemberCannotSpecifyNew = 30795
ERR_GenericSubMainsFound1 = 30796
ERR_GeneralProjectImportsError3 = 30797
ERR_InvalidTypeForAliasesImport2 = 30798
ERR_UnsupportedConstant2 = 30799
ERR_ObsoleteArgumentsNeedParens = 30800
ERR_ObsoleteLineNumbersAreLabels = 30801
ERR_ObsoleteStructureNotType = 30802
'ERR_ObsoleteDecimalNotCurrency = 30803 cut from Roslyn
ERR_ObsoleteObjectNotVariant = 30804
'ERR_ObsoleteArrayBounds = 30805 unused in Roslyn
ERR_ObsoleteLetSetNotNeeded = 30807
ERR_ObsoletePropertyGetLetSet = 30808
ERR_ObsoleteWhileWend = 30809
'ERR_ObsoleteStaticMethod = 30810 cut from Roslyn
ERR_ObsoleteRedimAs = 30811
ERR_ObsoleteOptionalWithoutValue = 30812
ERR_ObsoleteGosub = 30814
'ERR_ObsoleteFileIOKeywords1 = 30815 cut from Roslyn
'ERR_ObsoleteDebugKeyword1 = 30816 cut from Roslyn
ERR_ObsoleteOnGotoGosub = 30817
'ERR_ObsoleteMathCompatKeywords1 = 30818 cut from Roslyn
'ERR_ObsoleteMathKeywords2 = 30819 cut from Roslyn
'ERR_ObsoleteLsetKeyword1 = 30820 cut from Roslyn
'ERR_ObsoleteRsetKeyword1 = 30821 cut from Roslyn
'ERR_ObsoleteNullKeyword1 = 30822 cut from Roslyn
'ERR_ObsoleteEmptyKeyword1 = 30823 cut from Roslyn
ERR_ObsoleteEndIf = 30826
ERR_ObsoleteExponent = 30827
ERR_ObsoleteAsAny = 30828
ERR_ObsoleteGetStatement = 30829
'ERR_ObsoleteLineKeyword = 30830 cut from Roslyn
ERR_OverrideWithArrayVsParamArray2 = 30906
'// CONSIDER :harishk - improve this error message
ERR_CircularBaseDependencies4 = 30907
ERR_NestedBase2 = 30908
ERR_AccessMismatchOutsideAssembly4 = 30909
ERR_InheritanceAccessMismatchOutside3 = 30910
ERR_UseOfObsoletePropertyAccessor3 = 30911
ERR_UseOfObsoletePropertyAccessor2 = 30912
ERR_AccessMismatchImplementedEvent6 = 30914
ERR_AccessMismatchImplementedEvent4 = 30915
ERR_InheritanceCycleInImportedType1 = 30916
ERR_NoNonObsoleteConstructorOnBase3 = 30917
ERR_NoNonObsoleteConstructorOnBase4 = 30918
ERR_RequiredNonObsoleteNewCall3 = 30919
ERR_RequiredNonObsoleteNewCall4 = 30920
ERR_InheritsTypeArgAccessMismatch7 = 30921
ERR_InheritsTypeArgAccessMismatchOutside5 = 30922
'ERR_AccessMismatchTypeArgImplEvent7 = 30923 unused in Roslyn
'ERR_AccessMismatchTypeArgImplEvent5 = 30924 unused in Roslyn
ERR_PartialTypeAccessMismatch3 = 30925
ERR_PartialTypeBadMustInherit1 = 30926
ERR_MustOverOnNotInheritPartClsMem1 = 30927
ERR_BaseMismatchForPartialClass3 = 30928
ERR_PartialTypeTypeParamNameMismatch3 = 30931
ERR_PartialTypeConstraintMismatch1 = 30932
ERR_LateBoundOverloadInterfaceCall1 = 30933
ERR_RequiredAttributeConstConversion2 = 30934
ERR_AmbiguousOverrides3 = 30935
ERR_OverriddenCandidate1 = 30936
ERR_AmbiguousImplements3 = 30937
ERR_AddressOfNotCreatableDelegate1 = 30939
'ERR_ReturnFromEventMethod = 30940 unused in Roslyn
'ERR_BadEmptyStructWithCustomEvent1 = 30941
ERR_ComClassGenericMethod = 30943
ERR_SyntaxInCastOp = 30944
'ERR_UnimplementedBadMemberEvent = 30945 Cut in Roslyn
'ERR_EvaluationStopRequested = 30946
'ERR_EvaluationSuspendRequested = 30947
'ERR_EvaluationUnscheduledFiber = 30948
ERR_ArrayInitializerForNonConstDim = 30949
ERR_DelegateBindingFailure3 = 30950
'ERR_DelegateBindingTypeInferenceFails2 = 30952
'ERR_ConstraintViolationError1 = 30953
'ERR_ConstraintsFailedForInferredArgs2 = 30954
'ERR_TypeMismatchDLLProjectMix6 = 30955
'ERR_EvaluationPriorTimeout = 30957
'ERR_EvaluationENCObjectOutdated = 30958
' Obsolete ERR_TypeRefFromMetadataToVBUndef = 30960
'ERR_TypeMismatchMixedDLLs6 = 30961
'ERR_ReferencedAssemblyCausesCycle3 = 30962
'ERR_AssemblyRefAssembly2 = 30963
'ERR_AssemblyRefProject2 = 30964
'ERR_ProjectRefAssembly2 = 30965
'ERR_ProjectRefProject2 = 30966
'ERR_ReferencedAssembliesAmbiguous4 = 30967
'ERR_ReferencedAssembliesAmbiguous6 = 30968
'ERR_ReferencedProjectsAmbiguous4 = 30969
'ERR_GeneralErrorMixedDLLs5 = 30970
'ERR_GeneralErrorDLLProjectMix5 = 30971
ERR_StructLayoutAttributeNotAllowed = 30972
'ERR_ClassNotLoadedDuringDebugging = 30973
'ERR_UnableToEvaluateComment = 30974
'ERR_ForIndexInUse = 30975
'ERR_NextForMismatch = 30976
ERR_IterationVariableShadowLocal1 = 30978
ERR_InvalidOptionInfer = 30979
ERR_CircularInference1 = 30980
ERR_InAccessibleOverridingMethod5 = 30981
ERR_NoSuitableWidestType1 = 30982
ERR_AmbiguousWidestType3 = 30983
ERR_ExpectedAssignmentOperatorInInit = 30984
ERR_ExpectedQualifiedNameInInit = 30985
ERR_ExpectedLbrace = 30987
ERR_UnrecognizedTypeOrWith = 30988
ERR_DuplicateAggrMemberInit1 = 30989
ERR_NonFieldPropertyAggrMemberInit1 = 30990
ERR_SharedMemberAggrMemberInit1 = 30991
ERR_ParameterizedPropertyInAggrInit1 = 30992
ERR_NoZeroCountArgumentInitCandidates1 = 30993
ERR_AggrInitInvalidForObject = 30994
'ERR_BadWithRefInConstExpr = 30995
ERR_InitializerExpected = 30996
ERR_LineContWithCommentOrNoPrecSpace = 30999
' ERR_MemberNotFoundForNoPia = 31000 not used in Roslyn. This looks to be a VB EE message
ERR_InvInsideEnum = 31001
ERR_InvInsideBlock = 31002
ERR_UnexpectedExpressionStatement = 31003
ERR_WinRTEventWithoutDelegate = 31004
ERR_SecurityCriticalAsyncInClassOrStruct = 31005
ERR_SecurityCriticalAsync = 31006
ERR_BadModuleFile1 = 31007
ERR_BadRefLib1 = 31011
'ERR_UnableToLoadDll1 = 31013
'ERR_BadDllEntrypoint2 = 31014
'ERR_BadOutputFile1 = 31019
'ERR_BadOutputStream = 31020
'ERR_DeadBackgroundThread = 31021
'ERR_XMLParserError = 31023
'ERR_UnableToCreateMetaDataAPI = 31024
'ERR_UnableToOpenFile1 = 31027
ERR_EventHandlerSignatureIncompatible2 = 31029
ERR_ConditionalCompilationConstantNotValid = 31030
'ERR_ProjectCCError0 = 31031
ERR_InterfaceImplementedTwice1 = 31033
ERR_InterfaceNotImplemented1 = 31035
ERR_AmbiguousImplementsMember3 = 31040
'ERR_BadInterfaceMember = 31041
ERR_ImplementsOnNew = 31042
ERR_ArrayInitInStruct = 31043
ERR_EventTypeNotDelegate = 31044
ERR_ProtectedTypeOutsideClass = 31047
ERR_DefaultPropertyWithNoParams = 31048
ERR_InitializerInStruct = 31049
ERR_DuplicateImport1 = 31051
ERR_BadModuleFlags1 = 31052
ERR_ImplementsStmtWrongOrder = 31053
ERR_MemberConflictWithSynth4 = 31058
ERR_SynthMemberClashesWithSynth7 = 31059
ERR_SynthMemberClashesWithMember5 = 31060
ERR_MemberClashesWithSynth6 = 31061
ERR_SetHasOnlyOneParam = 31063
ERR_SetValueNotPropertyType = 31064
ERR_SetHasToBeByVal1 = 31065
ERR_StructureCantUseProtected = 31067
ERR_BadInterfaceDelegateSpecifier1 = 31068
ERR_BadInterfaceEnumSpecifier1 = 31069
ERR_BadInterfaceClassSpecifier1 = 31070
ERR_BadInterfaceStructSpecifier1 = 31071
'ERR_WarningTreatedAsError = 31072
'ERR_DelegateConstructorMissing1 = 31074 unused in Roslyn
ERR_UseOfObsoleteSymbolNoMessage1 = 31075
ERR_MetaDataIsNotAssembly = 31076
ERR_MetaDataIsNotModule = 31077
ERR_ReferenceComparison3 = 31080
ERR_CatchVariableNotLocal1 = 31082
ERR_ModuleMemberCantImplement = 31083
ERR_EventDelegatesCantBeFunctions = 31084
ERR_InvalidDate = 31085
ERR_CantOverride4 = 31086
ERR_CantSpecifyArraysOnBoth = 31087
ERR_NotOverridableRequiresOverrides = 31088
ERR_PrivateTypeOutsideType = 31089
ERR_TypeRefResolutionError3 = 31091
ERR_ParamArrayWrongType = 31092
ERR_CoClassMissing2 = 31094
ERR_InvalidMeReference = 31095
ERR_InvalidImplicitMeReference = 31096
ERR_RuntimeMemberNotFound2 = 31097
'ERR_RuntimeClassNotFound1 = 31098
ERR_BadPropertyAccessorFlags = 31099
ERR_BadPropertyAccessorFlagsRestrict = 31100
ERR_OnlyOneAccessorForGetSet = 31101
ERR_NoAccessibleSet = 31102
ERR_NoAccessibleGet = 31103
ERR_WriteOnlyNoAccessorFlag = 31104
ERR_ReadOnlyNoAccessorFlag = 31105
ERR_BadPropertyAccessorFlags1 = 31106
ERR_BadPropertyAccessorFlags2 = 31107
ERR_BadPropertyAccessorFlags3 = 31108
ERR_InAccessibleCoClass3 = 31109
ERR_MissingValuesForArraysInApplAttrs = 31110
ERR_ExitEventMemberNotInvalid = 31111
ERR_InvInsideEndsEvent = 31112
'ERR_EventMemberSyntax = 31113 abandoned per KevinH analysis. Roslyn bug 1637
ERR_MissingEndEvent = 31114
ERR_MissingEndAddHandler = 31115
ERR_MissingEndRemoveHandler = 31116
ERR_MissingEndRaiseEvent = 31117
'ERR_EndAddHandlerNotAtLineStart = 31118
'ERR_EndRemoveHandlerNotAtLineStart = 31119
'ERR_EndRaiseEventNotAtLineStart = 31120
ERR_CustomEventInvInInterface = 31121
ERR_CustomEventRequiresAs = 31122
ERR_InvalidEndEvent = 31123
ERR_InvalidEndAddHandler = 31124
ERR_InvalidEndRemoveHandler = 31125
ERR_InvalidEndRaiseEvent = 31126
ERR_DuplicateAddHandlerDef = 31127
ERR_DuplicateRemoveHandlerDef = 31128
ERR_DuplicateRaiseEventDef = 31129
ERR_MissingAddHandlerDef1 = 31130
ERR_MissingRemoveHandlerDef1 = 31131
ERR_MissingRaiseEventDef1 = 31132
ERR_EventAddRemoveHasOnlyOneParam = 31133
ERR_EventAddRemoveByrefParamIllegal = 31134
ERR_SpecifiersInvOnEventMethod = 31135
ERR_AddRemoveParamNotEventType = 31136
ERR_RaiseEventShapeMismatch1 = 31137
ERR_EventMethodOptionalParamIllegal1 = 31138
ERR_CantReferToMyGroupInsideGroupType1 = 31139
ERR_InvalidUseOfCustomModifier = 31140
ERR_InvalidOptionStrictCustom = 31141
ERR_ObsoleteInvalidOnEventMember = 31142
ERR_DelegateBindingIncompatible2 = 31143
ERR_ExpectedXmlName = 31146
ERR_UndefinedXmlPrefix = 31148
ERR_DuplicateXmlAttribute = 31149
ERR_MismatchedXmlEndTag = 31150
ERR_MissingXmlEndTag = 31151
ERR_ReservedXmlPrefix = 31152
ERR_MissingVersionInXmlDecl = 31153
ERR_IllegalAttributeInXmlDecl = 31154
ERR_QuotedEmbeddedExpression = 31155
ERR_VersionMustBeFirstInXmlDecl = 31156
ERR_AttributeOrder = 31157
'ERR_UnexpectedXmlName = 31158
ERR_ExpectedXmlEndEmbedded = 31159
ERR_ExpectedXmlEndPI = 31160
ERR_ExpectedXmlEndComment = 31161
ERR_ExpectedXmlEndCData = 31162
ERR_ExpectedSQuote = 31163
ERR_ExpectedQuote = 31164
ERR_ExpectedLT = 31165
ERR_StartAttributeValue = 31166
ERR_ExpectedDiv = 31167
ERR_NoXmlAxesLateBinding = 31168
ERR_IllegalXmlStartNameChar = 31169
ERR_IllegalXmlNameChar = 31170
ERR_IllegalXmlCommentChar = 31171
ERR_EmbeddedExpression = 31172
ERR_ExpectedXmlWhiteSpace = 31173
ERR_IllegalProcessingInstructionName = 31174
ERR_DTDNotSupported = 31175
'ERR_IllegalXmlChar = 31176 unused in Dev10
ERR_IllegalXmlWhiteSpace = 31177
ERR_ExpectedSColon = 31178
ERR_ExpectedXmlBeginEmbedded = 31179
ERR_XmlEntityReference = 31180
ERR_InvalidAttributeValue1 = 31181
ERR_InvalidAttributeValue2 = 31182
ERR_ReservedXmlNamespace = 31183
ERR_IllegalDefaultNamespace = 31184
'ERR_RequireAggregateInitializationImpl = 31185
ERR_QualifiedNameNotAllowed = 31186
ERR_ExpectedXmlns = 31187
'ERR_DefaultNamespaceNotSupported = 31188 Not reported by Dev10.
ERR_IllegalXmlnsPrefix = 31189
ERR_XmlFeaturesNotAvailable = 31190
'ERR_UnableToEmbedUacManifest = 31191 now reporting ErrorCreatingWin32ResourceFile
ERR_UnableToReadUacManifest2 = 31192
'ERR_UseValueForXmlExpression3 = 31193 ' Replaced by WRN_UseValueForXmlExpression3
ERR_TypeMismatchForXml3 = 31194
ERR_BinaryOperandsForXml4 = 31195
'ERR_XmlFeaturesNotAvailableDebugger = 31196
ERR_FullWidthAsXmlDelimiter = 31197
'ERR_XmlRequiresParens = 31198 No Longer Reported. Removed per 926946.
ERR_XmlEndCDataNotAllowedInContent = 31198
'ERR_UacALink3Missing = 31199 not used in Roslyn.
'ERR_XmlFeaturesNotSupported = 31200 not detected by the Roslyn compiler
ERR_EventImplRemoveHandlerParamWrong = 31201
ERR_MixingWinRTAndNETEvents = 31202
ERR_AddParamWrongForWinRT = 31203
ERR_RemoveParamWrongForWinRT = 31204
ERR_ReImplementingWinRTInterface5 = 31205
ERR_ReImplementingWinRTInterface4 = 31206
ERR_XmlEndElementNoMatchingStart = 31207
ERR_UndefinedTypeOrNamespace1 = 31208
ERR_BadInterfaceInterfaceSpecifier1 = 31209
ERR_TypeClashesWithVbCoreType4 = 31210
ERR_SecurityAttributeMissingAction = 31211
ERR_SecurityAttributeInvalidAction = 31212
ERR_SecurityAttributeInvalidActionAssembly = 31213
ERR_SecurityAttributeInvalidActionTypeOrMethod = 31214
ERR_PrincipalPermissionInvalidAction = 31215
ERR_PermissionSetAttributeInvalidFile = 31216
ERR_PermissionSetAttributeFileReadError = 31217
ERR_ExpectedWarningKeyword = 31218
ERR_InvalidHashAlgorithmName = 31219
'// NOTE: If you add any new errors that may be attached to a symbol during meta-import when it is marked as bad,
'// particularly if it applies to method symbols, please appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember.
'// Failure to do so may break customer code.
'// AVAILABLE 31220-31390
ERR_InvalidSubsystemVersion = 31391
ERR_LibAnycpu32bitPreferredConflict = 31392
ERR_RestrictedAccess = 31393
ERR_RestrictedConversion1 = 31394
ERR_NoTypecharInLabel = 31395
ERR_RestrictedType1 = 31396
ERR_NoTypecharInAlias = 31398
ERR_NoAccessibleConstructorOnBase = 31399
ERR_BadStaticLocalInStruct = 31400
ERR_DuplicateLocalStatic1 = 31401
ERR_ImportAliasConflictsWithType2 = 31403
ERR_CantShadowAMustOverride1 = 31404
'ERR_OptionalsCantBeStructs = 31405
ERR_MultipleEventImplMismatch3 = 31407
ERR_BadSpecifierCombo2 = 31408
ERR_MustBeOverloads2 = 31409
'ERR_CantOverloadOnMultipleInheritance = 31410
ERR_MustOverridesInClass1 = 31411
ERR_HandlesSyntaxInClass = 31412
ERR_SynthMemberShadowsMustOverride5 = 31413
'ERR_CantImplementNonVirtual3 = 31415 unused in Roslyn
' ERR_MemberShadowsSynthMustOverride5 = 31416 unused in Roslyn
ERR_CannotOverrideInAccessibleMember = 31417
ERR_HandlesSyntaxInModule = 31418
ERR_IsNotOpRequiresReferenceTypes1 = 31419
ERR_ClashWithReservedEnumMember1 = 31420
ERR_MultiplyDefinedEnumMember2 = 31421
ERR_BadUseOfVoid = 31422
ERR_EventImplMismatch5 = 31423
ERR_ForwardedTypeUnavailable3 = 31424
ERR_TypeFwdCycle2 = 31425
ERR_BadTypeInCCExpression = 31426
ERR_BadCCExpression = 31427
ERR_VoidArrayDisallowed = 31428
ERR_MetadataMembersAmbiguous3 = 31429
ERR_TypeOfExprAlwaysFalse2 = 31430
ERR_OnlyPrivatePartialMethods1 = 31431
ERR_PartialMethodsMustBePrivate = 31432
ERR_OnlyOnePartialMethodAllowed2 = 31433
ERR_OnlyOneImplementingMethodAllowed3 = 31434
ERR_PartialMethodMustBeEmpty = 31435
ERR_PartialMethodsMustBeSub1 = 31437
ERR_PartialMethodGenericConstraints2 = 31438
ERR_PartialDeclarationImplements1 = 31439
ERR_NoPartialMethodInAddressOf1 = 31440
ERR_ImplementationMustBePrivate2 = 31441
ERR_PartialMethodParamNamesMustMatch3 = 31442
ERR_PartialMethodTypeParamNameMismatch3 = 31443
ERR_PropertyDoesntImplementAllAccessors = 31444
ERR_InvalidAttributeUsageOnAccessor = 31445
ERR_NestedTypeInInheritsClause2 = 31446
ERR_TypeInItsInheritsClause1 = 31447
ERR_BaseTypeReferences2 = 31448
ERR_IllegalBaseTypeReferences3 = 31449
ERR_InvalidCoClass1 = 31450
ERR_InvalidOutputName = 31451
ERR_InvalidFileAlignment = 31452
ERR_InvalidDebugInformationFormat = 31453
'// NOTE: If you add any new errors that may be attached to a symbol during meta-import when it is marked as bad,
'// particularly if it applies to method symbols, please appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember.
'// Failure to do so may break customer code.
'// AVAILABLE 31451 - 31497
ERR_ConstantStringTooLong = 31498
ERR_MustInheritEventNotOverridden = 31499
ERR_BadAttributeSharedProperty1 = 31500
ERR_BadAttributeReadOnlyProperty1 = 31501
ERR_DuplicateResourceName1 = 31502
ERR_AttributeMustBeClassNotStruct1 = 31503
ERR_AttributeMustInheritSysAttr = 31504
'ERR_AttributeMustHaveAttrUsageAttr = 31505 unused in Roslyn.
ERR_AttributeCannotBeAbstract = 31506
' ERR_AttributeCannotHaveMustOverride = 31507 - reported by dev10 but error is redundant. ERR_AttributeCannotBeAbstract covers this case.
'ERR_CantFindCORSystemDirectory = 31508
ERR_UnableToOpenResourceFile1 = 31509
'ERR_BadAttributeConstField1 = 31510
ERR_BadAttributeNonPublicProperty1 = 31511
ERR_STAThreadAndMTAThread0 = 31512
'ERR_STAThreadAndMTAThread1 = 31513
'//If you make any change involving this error, such as creating a more specific version for use
'//in a particular context, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
ERR_IndirectUnreferencedAssembly4 = 31515
ERR_BadAttributeNonPublicType1 = 31516
ERR_BadAttributeNonPublicContType2 = 31517
'ERR_AlinkManifestFilepathTooLong = 31518 this scenario reports a more generic error
ERR_BadMetaDataReference1 = 31519
' ERR_ErrorApplyingSecurityAttribute1 = 31520 ' ' we're now reporting more detailed diagnostics: ERR_SecurityAttributeMissingAction, ERR_SecurityAttributeInvalidAction, ERR_SecurityAttributeInvalidActionAssembly or ERR_SecurityAttributeInvalidActionTypeOrMethod
'ERR_DuplicateModuleAttribute1 = 31521
ERR_DllImportOnNonEmptySubOrFunction = 31522
ERR_DllImportNotLegalOnDeclare = 31523
ERR_DllImportNotLegalOnGetOrSet = 31524
'ERR_TypeImportedFromDiffAssemVersions3 = 31525
ERR_DllImportOnGenericSubOrFunction = 31526
ERR_ComClassOnGeneric = 31527
'//If you make any change involving this error, such as creating a more specific version for use
'//in a particular context, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
'ERR_IndirectUnreferencedAssembly3 = 31528
ERR_DllImportOnInstanceMethod = 31529
ERR_DllImportOnInterfaceMethod = 31530
ERR_DllImportNotLegalOnEventMethod = 31531
'//If you make any change involving these errors, such as creating more specific versions for use
'//in other contexts, please make sure to appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember
'ERR_IndirectUnreferencedProject3 = 31532
'ERR_IndirectUnreferencedProject2 = 31533
ERR_FriendAssemblyBadArguments = 31534
ERR_FriendAssemblyStrongNameRequired = 31535
'ERR_FriendAssemblyRejectBinding = 31536 EDMAURER This has been replaced with two, more specific errors ERR_FriendRefNotEqualToThis and ERR_FriendRefSigningMismatch.
ERR_FriendAssemblyNameInvalid = 31537
ERR_FriendAssemblyBadAccessOverride2 = 31538
ERR_AbsentReferenceToPIA1 = 31539
'ERR_CorlibMissingPIAClasses1 = 31540 EDMAURER Roslyn uses the ordinary missing required type message
ERR_CannotLinkClassWithNoPIA1 = 31541
ERR_InvalidStructMemberNoPIA1 = 31542
ERR_NoPIAAttributeMissing2 = 31543
ERR_NestedGlobalNamespace = 31544
'ERR_NewCoClassNoPIA = 31545 EDMAURER Roslyn gives 31541
'ERR_EventNoPIANoDispID = 31546
'ERR_EventNoPIANoGuid1 = 31547
'ERR_EventNoPIANoComEventInterface1 = 31548
ERR_PIAHasNoAssemblyGuid1 = 31549
'ERR_StructureExplicitFieldLacksOffset = 31550
'ERR_CannotLinkEventInterfaceWithNoPIA1 = 31551
ERR_DuplicateLocalTypes3 = 31552
ERR_PIAHasNoTypeLibAttribute1 = 31553
' ERR_NoPiaEventsMissingSystemCore = 31554 use ordinary missing required type
' ERR_SourceInterfaceMustExist = 31555
ERR_SourceInterfaceMustBeInterface = 31556
ERR_EventNoPIANoBackingMember = 31557
ERR_NestedInteropType = 31558 ' used to be ERR_InvalidInteropType
ERR_IsNestedIn2 = 31559
ERR_LocalTypeNameClash2 = 31560
ERR_InteropMethodWithBody1 = 31561
ERR_UseOfLocalBeforeDeclaration1 = 32000
ERR_UseOfKeywordFromModule1 = 32001
'ERR_UseOfKeywordOutsideClass1 = 32002
'ERR_SymbolFromUnreferencedProject3 = 32004
ERR_BogusWithinLineIf = 32005
ERR_CharToIntegralTypeMismatch1 = 32006
ERR_IntegralToCharTypeMismatch1 = 32007
ERR_NoDirectDelegateConstruction1 = 32008
ERR_MethodMustBeFirstStatementOnLine = 32009
ERR_AttrAssignmentNotFieldOrProp1 = 32010
ERR_StrictDisallowsObjectComparison1 = 32013
ERR_NoConstituentArraySizes = 32014
ERR_FileAttributeNotAssemblyOrModule = 32015
ERR_FunctionResultCannotBeIndexed1 = 32016
ERR_ArgumentSyntax = 32017
ERR_ExpectedResumeOrGoto = 32019
ERR_ExpectedAssignmentOperator = 32020
ERR_NamedArgAlsoOmitted2 = 32021
ERR_CannotCallEvent1 = 32022
ERR_ForEachCollectionDesignPattern1 = 32023
ERR_DefaultValueForNonOptionalParam = 32024
' ERR_RegionWithinMethod = 32025 removed this limitation in Roslyn
'ERR_SpecifiersInvalidOnNamespace = 32026 abandoned, now giving 'Specifiers and attributes are not valid on this statement.'
ERR_ExpectedDotAfterMyBase = 32027
ERR_ExpectedDotAfterMyClass = 32028
ERR_StrictArgumentCopyBackNarrowing3 = 32029
ERR_LbElseifAfterElse = 32030
'ERR_EndSubNotAtLineStart = 32031
'ERR_EndFunctionNotAtLineStart = 32032
'ERR_EndGetNotAtLineStart = 32033
'ERR_EndSetNotAtLineStart = 32034
ERR_StandaloneAttribute = 32035
ERR_NoUniqueConstructorOnBase2 = 32036
ERR_ExtraNextVariable = 32037
ERR_RequiredNewCallTooMany2 = 32038
ERR_ForCtlVarArraySizesSpecified = 32039
ERR_BadFlagsOnNewOverloads = 32040
ERR_TypeCharOnGenericParam = 32041
ERR_TooFewGenericArguments1 = 32042
ERR_TooManyGenericArguments1 = 32043
ERR_GenericConstraintNotSatisfied2 = 32044
ERR_TypeOrMemberNotGeneric1 = 32045
ERR_NewIfNullOnGenericParam = 32046
ERR_MultipleClassConstraints1 = 32047
ERR_ConstNotClassInterfaceOrTypeParam1 = 32048
ERR_DuplicateTypeParamName1 = 32049
ERR_UnboundTypeParam2 = 32050
ERR_IsOperatorGenericParam1 = 32052
ERR_ArgumentCopyBackNarrowing3 = 32053
ERR_ShadowingGenericParamWithMember1 = 32054
ERR_GenericParamBase2 = 32055
ERR_ImplementsGenericParam = 32056
'ERR_ExpressionCannotBeGeneric1 = 32058 unused in Roslyn
ERR_OnlyNullLowerBound = 32059
ERR_ClassConstraintNotInheritable1 = 32060
ERR_ConstraintIsRestrictedType1 = 32061
ERR_GenericParamsOnInvalidMember = 32065
ERR_GenericArgsOnAttributeSpecifier = 32066
ERR_AttrCannotBeGenerics = 32067
ERR_BadStaticLocalInGenericMethod = 32068
ERR_SyntMemberShadowsGenericParam3 = 32070
ERR_ConstraintAlreadyExists1 = 32071
ERR_InterfacePossiblyImplTwice2 = 32072
ERR_ModulesCannotBeGeneric = 32073
ERR_GenericClassCannotInheritAttr = 32074
ERR_DeclaresCantBeInGeneric = 32075
'ERR_GenericTypeRequiresTypeArgs1 = 32076
ERR_OverrideWithConstraintMismatch2 = 32077
ERR_ImplementsWithConstraintMismatch3 = 32078
ERR_OpenTypeDisallowed = 32079
ERR_HandlesInvalidOnGenericMethod = 32080
ERR_MultipleNewConstraints = 32081
ERR_MustInheritForNewConstraint2 = 32082
ERR_NoSuitableNewForNewConstraint2 = 32083
ERR_BadGenericParamForNewConstraint2 = 32084
ERR_NewArgsDisallowedForTypeParam = 32085
ERR_DuplicateRawGenericTypeImport1 = 32086
ERR_NoTypeArgumentCountOverloadCand1 = 32087
ERR_TypeArgsUnexpected = 32088
ERR_NameSameAsMethodTypeParam1 = 32089
ERR_TypeParamNameFunctionNameCollision = 32090
'ERR_OverloadsMayUnify2 = 32091 unused in Roslyn
ERR_BadConstraintSyntax = 32092
ERR_OfExpected = 32093
ERR_ArrayOfRawGenericInvalid = 32095
ERR_ForEachAmbiguousIEnumerable1 = 32096
ERR_IsNotOperatorGenericParam1 = 32097
ERR_TypeParamQualifierDisallowed = 32098
ERR_TypeParamMissingCommaOrRParen = 32099
ERR_TypeParamMissingAsCommaOrRParen = 32100
ERR_MultipleReferenceConstraints = 32101
ERR_MultipleValueConstraints = 32102
ERR_NewAndValueConstraintsCombined = 32103
ERR_RefAndValueConstraintsCombined = 32104
ERR_BadTypeArgForStructConstraint2 = 32105
ERR_BadTypeArgForRefConstraint2 = 32106
ERR_RefAndClassTypeConstrCombined = 32107
ERR_ValueAndClassTypeConstrCombined = 32108
ERR_ConstraintClashIndirectIndirect4 = 32109
ERR_ConstraintClashDirectIndirect3 = 32110
ERR_ConstraintClashIndirectDirect3 = 32111
ERR_ConstraintCycleLink2 = 32112
ERR_ConstraintCycle2 = 32113
ERR_TypeParamWithStructConstAsConst = 32114
ERR_NullableDisallowedForStructConstr1 = 32115
'ERR_NoAccessibleNonGeneric1 = 32117
'ERR_NoAccessibleGeneric1 = 32118
ERR_ConflictingDirectConstraints3 = 32119
ERR_InterfaceUnifiesWithInterface2 = 32120
ERR_BaseUnifiesWithInterfaces3 = 32121
ERR_InterfaceBaseUnifiesWithBase4 = 32122
ERR_InterfaceUnifiesWithBase3 = 32123
ERR_OptionalsCantBeStructGenericParams = 32124 'TODO: remove
'ERR_InterfaceMethodImplsUnify3 = 32125
ERR_AddressOfNullableMethod = 32126
ERR_IsOperatorNullable1 = 32127
ERR_IsNotOperatorNullable1 = 32128
'ERR_NullableOnEnum = 32129
'ERR_NoNullableType = 32130 unused in Roslyn
ERR_ClassInheritsBaseUnifiesWithInterfaces3 = 32131
ERR_ClassInheritsInterfaceBaseUnifiesWithBase4 = 32132
ERR_ClassInheritsInterfaceUnifiesWithBase3 = 32133
ERR_ShadowingTypeOutsideClass1 = 32200
ERR_PropertySetParamCollisionWithValue = 32201
'ERR_EventNameTooLong = 32204 ' Deprecated in favor of ERR_TooLongMetadataName
'ERR_WithEventsNameTooLong = 32205 ' Deprecated in favor of ERR_TooLongMetadataName
ERR_SxSIndirectRefHigherThanDirectRef3 = 32207
ERR_DuplicateReference2 = 32208
'ERR_SxSLowerVerIndirectRefNotEmitted4 = 32209 not used in Roslyn
ERR_DuplicateReferenceStrong = 32210
ERR_IllegalCallOrIndex = 32303
ERR_ConflictDefaultPropertyAttribute = 32304
'ERR_ClassCannotCreated = 32400
ERR_BadAttributeUuid2 = 32500
ERR_ComClassAndReservedAttribute1 = 32501
ERR_ComClassRequiresPublicClass2 = 32504
ERR_ComClassReservedDispIdZero1 = 32505
ERR_ComClassReservedDispId1 = 32506
ERR_ComClassDuplicateGuids1 = 32507
ERR_ComClassCantBeAbstract0 = 32508
ERR_ComClassRequiresPublicClass1 = 32509
'ERR_DefaultCharSetAttributeNotSupported = 32510
ERR_UnknownOperator = 33000
ERR_DuplicateConversionCategoryUsed = 33001
ERR_OperatorNotOverloadable = 33002
ERR_InvalidHandles = 33003
ERR_InvalidImplements = 33004
ERR_EndOperatorExpected = 33005
ERR_EndOperatorNotAtLineStart = 33006
ERR_InvalidEndOperator = 33007
ERR_ExitOperatorNotValid = 33008
ERR_ParamArrayIllegal1 = 33009
ERR_OptionalIllegal1 = 33010
ERR_OperatorMustBePublic = 33011
ERR_OperatorMustBeShared = 33012
ERR_BadOperatorFlags1 = 33013
ERR_OneParameterRequired1 = 33014
ERR_TwoParametersRequired1 = 33015
ERR_OneOrTwoParametersRequired1 = 33016
ERR_ConvMustBeWideningOrNarrowing = 33017
ERR_OperatorDeclaredInModule = 33018
ERR_InvalidSpecifierOnNonConversion1 = 33019
ERR_UnaryParamMustBeContainingType1 = 33020
ERR_BinaryParamMustBeContainingType1 = 33021
ERR_ConvParamMustBeContainingType1 = 33022
ERR_OperatorRequiresBoolReturnType1 = 33023
ERR_ConversionToSameType = 33024
ERR_ConversionToInterfaceType = 33025
ERR_ConversionToBaseType = 33026
ERR_ConversionToDerivedType = 33027
ERR_ConversionToObject = 33028
ERR_ConversionFromInterfaceType = 33029
ERR_ConversionFromBaseType = 33030
ERR_ConversionFromDerivedType = 33031
ERR_ConversionFromObject = 33032
ERR_MatchingOperatorExpected2 = 33033
ERR_UnacceptableLogicalOperator3 = 33034
ERR_ConditionOperatorRequired3 = 33035
ERR_CopyBackTypeMismatch3 = 33037
ERR_ForLoopOperatorRequired2 = 33038
ERR_UnacceptableForLoopOperator2 = 33039
ERR_UnacceptableForLoopRelOperator2 = 33040
ERR_OperatorRequiresIntegerParameter1 = 33041
ERR_CantSpecifyNullableOnBoth = 33100
ERR_BadTypeArgForStructConstraintNull = 33101
ERR_CantSpecifyArrayAndNullableOnBoth = 33102
ERR_CantSpecifyTypeCharacterOnIIF = 33103
ERR_IllegalOperandInIIFCount = 33104
ERR_IllegalOperandInIIFName = 33105
ERR_IllegalOperandInIIFConversion = 33106
ERR_IllegalCondTypeInIIF = 33107
ERR_CantCallIIF = 33108
ERR_CantSpecifyAsNewAndNullable = 33109
ERR_IllegalOperandInIIFConversion2 = 33110
ERR_BadNullTypeInCCExpression = 33111
ERR_NullableImplicit = 33112
'// NOTE: If you add any new errors that may be attached to a symbol during meta-import when it is marked as bad,
'// particularly if it applies to method symbols, please appropriately modify Bindable::ResolveOverloadingShouldSkipBadMember.
'// Failure to do so may break customer code.
'// AVAILABLE 33113 - 34999
ERR_MissingRuntimeHelper = 35000
'ERR_NoStdModuleAttribute = 35001 ' Note: we're now reporting a use site error in this case.
'ERR_NoOptionTextAttribute = 35002
ERR_DuplicateResourceFileName1 = 35003
ERR_ExpectedDotAfterGlobalNameSpace = 36000
ERR_NoGlobalExpectedIdentifier = 36001
ERR_NoGlobalInHandles = 36002
ERR_ElseIfNoMatchingIf = 36005
ERR_BadAttributeConstructor2 = 36006
ERR_EndUsingWithoutUsing = 36007
ERR_ExpectedEndUsing = 36008
ERR_GotoIntoUsing = 36009
ERR_UsingRequiresDisposePattern = 36010
ERR_UsingResourceVarNeedsInitializer = 36011
ERR_UsingResourceVarCantBeArray = 36012
ERR_OnErrorInUsing = 36013
ERR_PropertyNameConflictInMyCollection = 36015
ERR_InvalidImplicitVar = 36016
ERR_ObjectInitializerRequiresFieldName = 36530
ERR_ExpectedFrom = 36531
ERR_LambdaBindingMismatch1 = 36532
ERR_CannotLiftByRefParamQuery1 = 36533
ERR_ExpressionTreeNotSupported = 36534
ERR_CannotLiftStructureMeQuery = 36535
ERR_InferringNonArrayType1 = 36536
ERR_ByRefParamInExpressionTree = 36538
'ERR_ObjectInitializerBadValue = 36543
'// If you change this message, make sure to change message for QueryDuplicateAnonTypeMemberName1 as well!
ERR_DuplicateAnonTypeMemberName1 = 36547
ERR_BadAnonymousTypeForExprTree = 36548
ERR_CannotLiftAnonymousType1 = 36549
ERR_ExtensionOnlyAllowedOnModuleSubOrFunction = 36550
ERR_ExtensionMethodNotInModule = 36551
ERR_ExtensionMethodNoParams = 36552
ERR_ExtensionMethodOptionalFirstArg = 36553
ERR_ExtensionMethodParamArrayFirstArg = 36554
'// If you change this message, make sure to change message for QueryAnonymousTypeFieldNameInference as well!
'ERR_BadOrCircularInitializerReference = 36555
ERR_AnonymousTypeFieldNameInference = 36556
ERR_NameNotMemberOfAnonymousType2 = 36557
ERR_ExtensionAttributeInvalid = 36558
ERR_AnonymousTypePropertyOutOfOrder1 = 36559
'// If you change this message, make sure to change message for QueryAnonymousTypeDisallowsTypeChar as well!
ERR_AnonymousTypeDisallowsTypeChar = 36560
ERR_ExtensionMethodUncallable1 = 36561
ERR_ExtensionMethodOverloadCandidate3 = 36562
ERR_DelegateBindingMismatch = 36563
ERR_DelegateBindingTypeInferenceFails = 36564
ERR_TooManyArgs = 36565
ERR_NamedArgAlsoOmitted1 = 36566
ERR_NamedArgUsedTwice1 = 36567
ERR_NamedParamNotFound1 = 36568
ERR_OmittedArgument1 = 36569
ERR_UnboundTypeParam1 = 36572
ERR_ExtensionMethodOverloadCandidate2 = 36573
ERR_AnonymousTypeNeedField = 36574
ERR_AnonymousTypeNameWithoutPeriod = 36575
ERR_AnonymousTypeExpectedIdentifier = 36576
'ERR_NoAnonymousTypeInitializersInDebugger = 36577
'ERR_TooFewGenericArguments = 36578
'ERR_TooManyGenericArguments = 36579
'ERR_DelegateBindingMismatch3_3 = 36580 unused in Roslyn
'ERR_DelegateBindingTypeInferenceFails3 = 36581
ERR_TooManyArgs2 = 36582
ERR_NamedArgAlsoOmitted3 = 36583
ERR_NamedArgUsedTwice3 = 36584
ERR_NamedParamNotFound3 = 36585
ERR_OmittedArgument3 = 36586
ERR_UnboundTypeParam3 = 36589
ERR_TooFewGenericArguments2 = 36590
ERR_TooManyGenericArguments2 = 36591
ERR_ExpectedInOrEq = 36592
ERR_ExpectedQueryableSource = 36593
ERR_QueryOperatorNotFound = 36594
ERR_CannotUseOnErrorGotoWithClosure = 36595
ERR_CannotGotoNonScopeBlocksWithClosure = 36597
ERR_CannotLiftRestrictedTypeQuery = 36598
ERR_QueryAnonymousTypeFieldNameInference = 36599
ERR_QueryDuplicateAnonTypeMemberName1 = 36600
ERR_QueryAnonymousTypeDisallowsTypeChar = 36601
ERR_ReadOnlyInClosure = 36602
ERR_ExprTreeNoMultiDimArrayCreation = 36603
ERR_ExprTreeNoLateBind = 36604
ERR_ExpectedBy = 36605
ERR_QueryInvalidControlVariableName1 = 36606
ERR_ExpectedIn = 36607
'ERR_QueryStartsWithLet = 36608
'ERR_NoQueryExpressionsInDebugger = 36609
ERR_QueryNameNotDeclared = 36610
ERR_SharedEventNeedsHandlerInTheSameType = 36611
ERR_NestedFunctionArgumentNarrowing3 = 36612
'// If you change this message, make sure to change message for QueryAnonTypeFieldXMLNameInference as well!
ERR_AnonTypeFieldXMLNameInference = 36613
ERR_QueryAnonTypeFieldXMLNameInference = 36614
ERR_ExpectedInto = 36615
'ERR_AggregateStartsWithLet = 36616
ERR_TypeCharOnAggregation = 36617
ERR_ExpectedOn = 36618
ERR_ExpectedEquals = 36619
ERR_ExpectedAnd = 36620
ERR_EqualsTypeMismatch = 36621
ERR_EqualsOperandIsBad = 36622
'// see 30581 (lambda version of addressof)
ERR_LambdaNotDelegate1 = 36625
'// see 30939 (lambda version of addressof)
ERR_LambdaNotCreatableDelegate1 = 36626
'ERR_NoLambdaExpressionsInDebugger = 36627
ERR_CannotInferNullableForVariable1 = 36628
ERR_NullableTypeInferenceNotSupported = 36629
ERR_ExpectedJoin = 36631
ERR_NullableParameterMustSpecifyType = 36632
ERR_IterationVariableShadowLocal2 = 36633
ERR_LambdasCannotHaveAttributes = 36634
ERR_LambdaInSelectCaseExpr = 36635
ERR_AddressOfInSelectCaseExpr = 36636
ERR_NullableCharNotSupported = 36637
'// The follow error messages are paired with other query specific messages above. Please
'// make sure to keep the two in sync
ERR_CannotLiftStructureMeLambda = 36638
ERR_CannotLiftByRefParamLambda1 = 36639
ERR_CannotLiftRestrictedTypeLambda = 36640
ERR_LambdaParamShadowLocal1 = 36641
ERR_StrictDisallowImplicitObjectLambda = 36642
ERR_CantSpecifyParamsOnLambdaParamNoType = 36643
ERR_TypeInferenceFailure1 = 36644
ERR_TypeInferenceFailure2 = 36645
ERR_TypeInferenceFailure3 = 36646
ERR_TypeInferenceFailureNoExplicit1 = 36647
ERR_TypeInferenceFailureNoExplicit2 = 36648
ERR_TypeInferenceFailureNoExplicit3 = 36649
ERR_TypeInferenceFailureAmbiguous1 = 36650
ERR_TypeInferenceFailureAmbiguous2 = 36651
ERR_TypeInferenceFailureAmbiguous3 = 36652
ERR_TypeInferenceFailureNoExplicitAmbiguous1 = 36653
ERR_TypeInferenceFailureNoExplicitAmbiguous2 = 36654
ERR_TypeInferenceFailureNoExplicitAmbiguous3 = 36655
ERR_TypeInferenceFailureNoBest1 = 36656
ERR_TypeInferenceFailureNoBest2 = 36657
ERR_TypeInferenceFailureNoBest3 = 36658
ERR_TypeInferenceFailureNoExplicitNoBest1 = 36659
ERR_TypeInferenceFailureNoExplicitNoBest2 = 36660
ERR_TypeInferenceFailureNoExplicitNoBest3 = 36661
ERR_DelegateBindingMismatchStrictOff2 = 36663
'ERR_TooDeepNestingOfParensInLambdaParam = 36664 - No Longer Reported. Removed per 926942
' ERR_InaccessibleReturnTypeOfSymbol1 = 36665
ERR_InaccessibleReturnTypeOfMember2 = 36666
ERR_LocalNamedSameAsParamInLambda1 = 36667
ERR_MultilineLambdasCannotContainOnError = 36668
'ERR_BranchOutOfMultilineLambda = 36669 obsolete - was not even reported in Dev10 any more.
ERR_LambdaBindingMismatch2 = 36670
'ERR_MultilineLambdaShadowLocal1 = 36671 'unused in Roslyn
ERR_StaticInLambda = 36672
ERR_MultilineLambdaMissingSub = 36673
ERR_MultilineLambdaMissingFunction = 36674
ERR_StatementLambdaInExpressionTree = 36675
' //ERR_StrictDisallowsImplicitLambda = 36676
' // replaced by LambdaNoType and LambdaNoTypeObjectDisallowed and LambdaTooManyTypesObjectDisallowed
ERR_AttributeOnLambdaReturnType = 36677
ERR_ExpectedIdentifierOrGroup = 36707
ERR_UnexpectedGroup = 36708
ERR_DelegateBindingMismatchStrictOff3 = 36709
ERR_DelegateBindingIncompatible3 = 36710
ERR_ArgumentNarrowing2 = 36711
ERR_OverloadCandidate1 = 36712
ERR_AutoPropertyInitializedInStructure = 36713
ERR_InitializedExpandedProperty = 36714
'ERR_NewExpandedProperty = 36715 'unused in Roslyn
ERR_LanguageVersion = 36716
ERR_ArrayInitNoType = 36717
ERR_NotACollection1 = 36718
ERR_NoAddMethod1 = 36719
ERR_CantCombineInitializers = 36720
ERR_EmptyAggregateInitializer = 36721
ERR_VarianceDisallowedHere = 36722
ERR_VarianceInterfaceNesting = 36723
ERR_VarianceOutParamDisallowed1 = 36724
ERR_VarianceInParamDisallowed1 = 36725
ERR_VarianceOutParamDisallowedForGeneric3 = 36726
ERR_VarianceInParamDisallowedForGeneric3 = 36727
ERR_VarianceOutParamDisallowedHere2 = 36728
ERR_VarianceInParamDisallowedHere2 = 36729
ERR_VarianceOutParamDisallowedHereForGeneric4 = 36730
ERR_VarianceInParamDisallowedHereForGeneric4 = 36731
ERR_VarianceTypeDisallowed2 = 36732
ERR_VarianceTypeDisallowedForGeneric4 = 36733
ERR_LambdaTooManyTypesObjectDisallowed = 36734
ERR_VarianceTypeDisallowedHere3 = 36735
ERR_VarianceTypeDisallowedHereForGeneric5 = 36736
ERR_AmbiguousCastConversion2 = 36737
ERR_VariancePreventsSynthesizedEvents2 = 36738
ERR_NestingViolatesCLS1 = 36739
ERR_VarianceOutNullableDisallowed2 = 36740
ERR_VarianceInNullableDisallowed2 = 36741
ERR_VarianceOutByValDisallowed1 = 36742
ERR_VarianceInReturnDisallowed1 = 36743
ERR_VarianceOutConstraintDisallowed1 = 36744
ERR_VarianceInReadOnlyPropertyDisallowed1 = 36745
ERR_VarianceOutWriteOnlyPropertyDisallowed1 = 36746
ERR_VarianceOutPropertyDisallowed1 = 36747
ERR_VarianceInPropertyDisallowed1 = 36748
ERR_VarianceOutByRefDisallowed1 = 36749
ERR_VarianceInByRefDisallowed1 = 36750
ERR_LambdaNoType = 36751
' //ERR_NoReturnStatementsForMultilineLambda = 36752
' // replaced by LambdaNoType and LambdaNoTypeObjectDisallowed
'ERR_CollectionInitializerArity2 = 36753
ERR_VarianceConversionFailedOut6 = 36754
ERR_VarianceConversionFailedIn6 = 36755
ERR_VarianceIEnumerableSuggestion3 = 36756
ERR_VarianceConversionFailedTryOut4 = 36757
ERR_VarianceConversionFailedTryIn4 = 36758
ERR_AutoPropertyCantHaveParams = 36759
ERR_IdentityDirectCastForFloat = 36760
ERR_TypeDisallowsElements = 36807
ERR_TypeDisallowsAttributes = 36808
ERR_TypeDisallowsDescendants = 36809
'ERR_XmlSchemaCompileError = 36810
ERR_TypeOrMemberNotGeneric2 = 36907
ERR_ExtensionMethodCannotBeLateBound = 36908
ERR_TypeInferenceArrayRankMismatch1 = 36909
ERR_QueryStrictDisallowImplicitObject = 36910
ERR_IfNoType = 36911
ERR_IfNoTypeObjectDisallowed = 36912
ERR_IfTooManyTypesObjectDisallowed = 36913
ERR_ArrayInitNoTypeObjectDisallowed = 36914
ERR_ArrayInitTooManyTypesObjectDisallowed = 36915
ERR_LambdaNoTypeObjectDisallowed = 36916
ERR_OverloadsModifierInModule = 36917
ERR_SubRequiresSingleStatement = 36918
ERR_SubDisallowsStatement = 36919
ERR_SubRequiresParenthesesLParen = 36920
ERR_SubRequiresParenthesesDot = 36921
ERR_SubRequiresParenthesesBang = 36922
ERR_CannotEmbedInterfaceWithGeneric = 36923
ERR_CannotUseGenericTypeAcrossAssemblyBoundaries = 36924
ERR_CannotUseGenericBaseTypeAcrossAssemblyBoundaries = 36925
ERR_BadAsyncByRefParam = 36926
ERR_BadIteratorByRefParam = 36927
'ERR_BadAsyncExpressionLambda = 36928 'unused in Roslyn
ERR_BadAsyncInQuery = 36929
ERR_BadGetAwaiterMethod1 = 36930
'ERR_ExpressionTreeContainsAwait = 36931
ERR_RestrictedResumableType1 = 36932
ERR_BadAwaitNothing = 36933
ERR_AsyncSubMain = 36934
ERR_PartialMethodsMustNotBeAsync1 = 36935
ERR_InvalidAsyncIteratorModifiers = 36936
ERR_BadAwaitNotInAsyncMethodOrLambda = 36937
ERR_BadIteratorReturn = 36938
ERR_BadYieldInTryHandler = 36939
ERR_BadYieldInNonIteratorMethod = 36940
'// unused 36941
ERR_BadReturnValueInIterator = 36942
ERR_BadAwaitInTryHandler = 36943
'ERR_BadAwaitObject = 36944 'unused in Roslyn
ERR_BadAsyncReturn = 36945
ERR_BadResumableAccessReturnVariable = 36946
ERR_BadIteratorExpressionLambda = 36947
'ERR_AwaitLibraryMissing = 36948
'ERR_AwaitPattern1 = 36949
ERR_ConstructorAsync = 36950
ERR_InvalidLambdaModifier = 36951
ERR_ReturnFromNonGenericTaskAsync = 36952
'ERR_BadAutoPropertyFlags1 = 36953 'unused in Roslyn
ERR_BadOverloadCandidates2 = 36954
ERR_BadStaticInitializerInResumable = 36955
ERR_ResumablesCannotContainOnError = 36956
ERR_FriendRefNotEqualToThis = 36957
ERR_FriendRefSigningMismatch = 36958
ERR_FailureSigningAssembly = 36960
ERR_SignButNoPrivateKey = 36961
ERR_InvalidVersionFormat = 36962
ERR_ExpectedSingleScript = 36963
ERR_ReferenceDirectiveOnlyAllowedInScripts = 36964
ERR_NamespaceNotAllowedInScript = 36965
ERR_KeywordNotAllowedInScript = 36966
ERR_ReservedAssemblyName = 36968
ERR_ConstructorCannotBeDeclaredPartial = 36969
ERR_ModuleEmitFailure = 36970
ERR_ParameterNotValidForType = 36971
ERR_MarshalUnmanagedTypeNotValidForFields = 36972
ERR_MarshalUnmanagedTypeOnlyValidForFields = 36973
ERR_AttributeParameterRequired1 = 36974
ERR_AttributeParameterRequired2 = 36975
ERR_InvalidVersionFormat2 = 36976
ERR_InvalidAssemblyCultureForExe = 36977
ERR_InvalidMultipleAttributeUsageInNetModule2 = 36978
ERR_SecurityAttributeInvalidTarget = 36979
ERR_PublicKeyFileFailure = 36980
ERR_PublicKeyContainerFailure = 36981
ERR_InvalidAssemblyCulture = 36982
ERR_EncUpdateFailedMissingAttribute = 36983
ERR_CantAwaitAsyncSub1 = 37001
ERR_ResumableLambdaInExpressionTree = 37050
ERR_DllImportOnResumableMethod = 37051
ERR_CannotLiftRestrictedTypeResumable1 = 37052
ERR_BadIsCompletedOnCompletedGetResult2 = 37053
ERR_SynchronizedAsyncMethod = 37054
ERR_BadAsyncReturnOperand1 = 37055
ERR_DoesntImplementAwaitInterface2 = 37056
ERR_BadAwaitInNonAsyncMethod = 37057
ERR_BadAwaitInNonAsyncVoidMethod = 37058
ERR_BadAwaitInNonAsyncLambda = 37059
ERR_LoopControlMustNotAwait = 37060
ERR_MyGroupCollectionAttributeCycle = 37201
ERR_LiteralExpected = 37202
ERR_PartialMethodDefaultParameterValueMismatch2 = 37203
ERR_PartialMethodParamArrayMismatch2 = 37204
ERR_NetModuleNameMismatch = 37205
ERR_BadModuleName = 37206
ERR_CmdOptionConflictsSource = 37207
ERR_TypeForwardedToMultipleAssemblies = 37208
ERR_InvalidSignaturePublicKey = 37209
ERR_CollisionWithPublicTypeInModule = 37210
ERR_ExportedTypeConflictsWithDeclaration = 37211
ERR_ExportedTypesConflict = 37212
ERR_AgnosticToMachineModule = 37213
ERR_ConflictingMachineModule = 37214
ERR_CryptoHashFailed = 37215
ERR_CantHaveWin32ResAndManifest = 37216
ERR_ForwardedTypeConflictsWithDeclaration = 37217
ERR_ForwardedTypeConflictsWithExportedType = 37218
ERR_ForwardedTypesConflict = 37219
ERR_TooLongMetadataName = 37220
ERR_MissingNetModuleReference = 37221
ERR_UnsupportedModule1 = 37222
ERR_UnsupportedEvent1 = 37223
ERR_NetModuleNameMustBeUnique = 37224
ERR_PDBWritingFailed = 37225
ERR_ParamDefaultValueDiffersFromAttribute = 37226
ERR_ResourceInModule = 37227
ERR_FieldHasMultipleDistinctConstantValues = 37228
ERR_AmbiguousInNamespaces2 = 37229
ERR_EncNoPIAReference = 37230
ERR_LinkedNetmoduleMetadataMustProvideFullPEImage = 37231
ERR_CantReadRulesetFile = 37232
ERR_MetadataReferencesNotSupported = 37233
ERR_PlatformDoesntSupport = 37234
ERR_CantUseRequiredAttribute = 37235
ERR_EncodinglessSyntaxTree = 37236
ERR_InvalidFormatSpecifier = 37237
ERR_CannotBeMadeNullable1 = 37238
ERR_BadConditionalWithRef = 37239
ERR_NullPropagatingOpInExpressionTree = 37240
ERR_TooLongOrComplexExpression = 37241
ERR_BadPdbData = 37242
ERR_AutoPropertyCantBeWriteOnly = 37243
ERR_ExpressionDoesntHaveName = 37244
ERR_InvalidNameOfSubExpression = 37245
ERR_MethodTypeArgsUnexpected = 37246
ERR_InReferencedAssembly = 37247
ERR_EncReferenceToAddedMember = 37248
ERR_InterpolationFormatWhitespace = 37249
ERR_InterpolationAlignmentOutOfRange = 37250
ERR_InterpolatedStringFactoryError = 37251
ERR_DebugEntryPointNotSourceMethodDefinition = 37252
ERR_InvalidPathMap = 37253
ERR_PublicSignNoKey = 37254
ERR_TooManyUserStrings = 37255
ERR_PeWritingFailure = 37256
ERR_OptionMustBeAbsolutePath = 37257
ERR_DocFileGen = 37258
ERR_TupleTooFewElements = 37259
ERR_TupleReservedElementNameAnyPosition = 37260
ERR_TupleReservedElementName = 37261
ERR_TupleDuplicateElementName = 37262
ERR_RefReturningCallInExpressionTree = 37263
ERR_SourceLinkRequiresPdb = 37264
ERR_CannotEmbedWithoutPdb = 37265
ERR_InvalidInstrumentationKind = 37266
ERR_ValueTupleTypeRefResolutionError1 = 37267
ERR_TupleElementNamesAttributeMissing = 37268
ERR_ExplicitTupleElementNamesAttribute = 37269
ERR_TupleLiteralDisallowsTypeChar = 37270
ERR_DuplicateProcDefWithDifferentTupleNames2 = 37271
ERR_InterfaceImplementedTwiceWithDifferentTupleNames2 = 37272
ERR_InterfaceImplementedTwiceWithDifferentTupleNames3 = 37273
ERR_InterfaceImplementedTwiceWithDifferentTupleNamesReverse3 = 37274
ERR_InterfaceImplementedTwiceWithDifferentTupleNames4 = 37275
ERR_InterfaceInheritedTwiceWithDifferentTupleNames2 = 37276
ERR_InterfaceInheritedTwiceWithDifferentTupleNames3 = 37277
ERR_InterfaceInheritedTwiceWithDifferentTupleNamesReverse3 = 37278
ERR_InterfaceInheritedTwiceWithDifferentTupleNames4 = 37279
ERR_NewWithTupleTypeSyntax = 37280
ERR_PredefinedValueTupleTypeMustBeStruct = 37281
ERR_PublicSignNetModule = 37282
ERR_BadAssemblyName = 37283
ERR_Merge_conflict_marker_encountered = 37284
ERR_BadSourceCodeKind = 37285
ERR_BadDocumentationMode = 37286
ERR_BadLanguageVersion = 37287
ERR_InvalidPreprocessorConstantType = 37288
ERR_TupleInferredNamesNotAvailable = 37289
ERR_InvalidDebugInfo = 37290
ERR_NoRefOutWhenRefOnly = 37300
ERR_NoNetModuleOutputWhenRefOutOrRefOnly = 37301
ERR_BadNonTrailingNamedArgument = 37302
ERR_ExpectedNamedArgumentInAttributeList = 37303
ERR_NamedArgumentSpecificationBeforeFixedArgumentInLateboundInvocation = 37304
ERR_ValueTupleResolutionAmbiguous3 = 37305
ERR_CommentsAfterLineContinuationNotAvailable1 = 37306
ERR_DefaultInterfaceImplementationInNoPIAType = 37307
ERR_ReAbstractionInNoPIAType = 37308
ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation = 37309
ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember = 37310
ERR_AssignmentInitOnly = 37311
ERR_OverridingInitOnlyProperty = 37312
ERR_PropertyDoesntImplementInitOnly = 37313
'// WARNINGS BEGIN HERE
WRN_UseOfObsoleteSymbol2 = 40000
WRN_InvalidOverrideDueToTupleNames2 = 40001
WRN_MustOverloadBase4 = 40003
WRN_OverrideType5 = 40004
WRN_MustOverride2 = 40005
WRN_DefaultnessShadowed4 = 40007
WRN_UseOfObsoleteSymbolNoMessage1 = 40008
WRN_AssemblyGeneration0 = 40009
WRN_AssemblyGeneration1 = 40010
WRN_ComClassNoMembers1 = 40011
WRN_SynthMemberShadowsMember5 = 40012
WRN_MemberShadowsSynthMember6 = 40014
WRN_SynthMemberShadowsSynthMember7 = 40018
WRN_UseOfObsoletePropertyAccessor3 = 40019
WRN_UseOfObsoletePropertyAccessor2 = 40020
' WRN_MemberShadowsMemberInModule5 = 40021 ' no repro in legacy test, most probably not reachable. Unused in Roslyn.
' WRN_SynthMemberShadowsMemberInModule5 = 40022 ' no repro in legacy test, most probably not reachable. Unused in Roslyn.
' WRN_MemberShadowsSynthMemberInModule6 = 40023 ' no repro in legacy test, most probably not reachable. Unused in Roslyn.
' WRN_SynthMemberShadowsSynthMemberMod7 = 40024 ' no repro in legacy test, most probably not reachable. Unused in Roslyn.
WRN_FieldNotCLSCompliant1 = 40025
WRN_BaseClassNotCLSCompliant2 = 40026
WRN_ProcTypeNotCLSCompliant1 = 40027
WRN_ParamNotCLSCompliant1 = 40028
WRN_InheritedInterfaceNotCLSCompliant2 = 40029
WRN_CLSMemberInNonCLSType3 = 40030
WRN_NameNotCLSCompliant1 = 40031
WRN_EnumUnderlyingTypeNotCLS1 = 40032
WRN_NonCLSMemberInCLSInterface1 = 40033
WRN_NonCLSMustOverrideInCLSType1 = 40034
WRN_ArrayOverloadsNonCLS2 = 40035
WRN_RootNamespaceNotCLSCompliant1 = 40038
WRN_RootNamespaceNotCLSCompliant2 = 40039
WRN_GenericConstraintNotCLSCompliant1 = 40040
WRN_TypeNotCLSCompliant1 = 40041
WRN_OptionalValueNotCLSCompliant1 = 40042
WRN_CLSAttrInvalidOnGetSet = 40043
WRN_TypeConflictButMerged6 = 40046
' WRN_TypeConflictButMerged7 = 40047 ' deprecated
WRN_ShadowingGenericParamWithParam1 = 40048
WRN_CannotFindStandardLibrary1 = 40049
WRN_EventDelegateTypeNotCLSCompliant2 = 40050
WRN_DebuggerHiddenIgnoredOnProperties = 40051
WRN_SelectCaseInvalidRange = 40052
WRN_CLSEventMethodInNonCLSType3 = 40053
WRN_ExpectedInitComponentCall2 = 40054
WRN_NamespaceCaseMismatch3 = 40055
WRN_UndefinedOrEmptyNamespaceOrClass1 = 40056
WRN_UndefinedOrEmptyProjectNamespaceOrClass1 = 40057
'WRN_InterfacesWithNoPIAMustHaveGuid1 = 40058 ' Not reported by Dev11.
WRN_IndirectRefToLinkedAssembly2 = 40059
WRN_DelaySignButNoKey = 40060
WRN_UnimplementedCommandLineSwitch = 40998
' WRN_DuplicateAssemblyAttribute1 = 41000 'unused in Roslyn
WRN_NoNonObsoleteConstructorOnBase3 = 41001
WRN_NoNonObsoleteConstructorOnBase4 = 41002
WRN_RequiredNonObsoleteNewCall3 = 41003
WRN_RequiredNonObsoleteNewCall4 = 41004
WRN_MissingAsClauseinOperator = 41005
WRN_ConstraintsFailedForInferredArgs2 = 41006
WRN_ConditionalNotValidOnFunction = 41007
WRN_UseSwitchInsteadOfAttribute = 41008
WRN_TupleLiteralNameMismatch = 41009
'// AVAILABLE 41010 - 41199
WRN_ReferencedAssemblyDoesNotHaveStrongName = 41997
WRN_RecursiveAddHandlerCall = 41998
WRN_ImplicitConversionCopyBack = 41999
WRN_MustShadowOnMultipleInheritance2 = 42000
' WRN_ObsoleteClassInitialize = 42001 ' deprecated
' WRN_ObsoleteClassTerminate = 42002 ' deprecated
WRN_RecursiveOperatorCall = 42004
' WRN_IndirectlyImplementedBaseMember5 = 42014 ' deprecated
' WRN_ImplementedBaseMember4 = 42015 ' deprecated
WRN_ImplicitConversionSubst1 = 42016 '// populated by 42350/42332/42336/42337/42338/42339/42340
WRN_LateBindingResolution = 42017
WRN_ObjectMath1 = 42018
WRN_ObjectMath2 = 42019
WRN_ObjectAssumedVar1 = 42020 ' // populated by 42111/42346
WRN_ObjectAssumed1 = 42021 ' // populated by 42347/41005/42341/42342/42344/42345/42334/42343
WRN_ObjectAssumedProperty1 = 42022 ' // populated by 42348
'// AVAILABLE 42023
WRN_UnusedLocal = 42024
WRN_SharedMemberThroughInstance = 42025
WRN_RecursivePropertyCall = 42026
WRN_OverlappingCatch = 42029
WRN_DefAsgUseNullRefByRef = 42030
WRN_DuplicateCatch = 42031
WRN_ObjectMath1Not = 42032
WRN_BadChecksumValExtChecksum = 42033
WRN_MultipleDeclFileExtChecksum = 42034
WRN_BadGUIDFormatExtChecksum = 42035
WRN_ObjectMathSelectCase = 42036
WRN_EqualToLiteralNothing = 42037
WRN_NotEqualToLiteralNothing = 42038
'// AVAILABLE 42039 - 42098
WRN_UnusedLocalConst = 42099
'// UNAVAILABLE 42100
WRN_ComClassInterfaceShadows5 = 42101
WRN_ComClassPropertySetObject1 = 42102
'// only reference types are considered for definite assignment.
'// DefAsg's are all under VB_advanced
WRN_DefAsgUseNullRef = 42104
WRN_DefAsgNoRetValFuncRef1 = 42105
WRN_DefAsgNoRetValOpRef1 = 42106
WRN_DefAsgNoRetValPropRef1 = 42107
WRN_DefAsgUseNullRefByRefStr = 42108
WRN_DefAsgUseNullRefStr = 42109
' WRN_FieldInForNotExplicit = 42110 'unused in Roslyn
WRN_StaticLocalNoInference = 42111
'// AVAILABLE 42112 - 42202
' WRN_SxSHigherIndirectRefEmitted4 = 42203 'unused in Roslyn
' WRN_ReferencedAssembliesAmbiguous6 = 42204 'unused in Roslyn
' WRN_ReferencedAssembliesAmbiguous4 = 42205 'unused in Roslyn
' WRN_MaximumNumberOfWarnings = 42206 'unused in Roslyn
WRN_InvalidAssemblyName = 42207
'// AVAILABLE 42209 - 42299
WRN_XMLDocBadXMLLine = 42300
WRN_XMLDocMoreThanOneCommentBlock = 42301
WRN_XMLDocNotFirstOnLine = 42302
WRN_XMLDocInsideMethod = 42303
WRN_XMLDocParseError1 = 42304
WRN_XMLDocDuplicateXMLNode1 = 42305
WRN_XMLDocIllegalTagOnElement2 = 42306
WRN_XMLDocBadParamTag2 = 42307
WRN_XMLDocParamTagWithoutName = 42308
WRN_XMLDocCrefAttributeNotFound1 = 42309
WRN_XMLMissingFileOrPathAttribute1 = 42310
WRN_XMLCannotWriteToXMLDocFile2 = 42311
WRN_XMLDocWithoutLanguageElement = 42312
WRN_XMLDocReturnsOnWriteOnlyProperty = 42313
WRN_XMLDocOnAPartialType = 42314
WRN_XMLDocReturnsOnADeclareSub = 42315
WRN_XMLDocStartTagWithNoEndTag = 42316
WRN_XMLDocBadGenericParamTag2 = 42317
WRN_XMLDocGenericParamTagWithoutName = 42318
WRN_XMLDocExceptionTagWithoutCRef = 42319
WRN_XMLDocInvalidXMLFragment = 42320
WRN_XMLDocBadFormedXML = 42321
WRN_InterfaceConversion2 = 42322
WRN_LiftControlVariableLambda = 42324
' 42325 unused, was abandoned, now used in unit test "EnsureLegacyWarningsAreMaintained". Please update test if you are going to use this number.
WRN_LambdaPassedToRemoveHandler = 42326
WRN_LiftControlVariableQuery = 42327
WRN_RelDelegatePassedToRemoveHandler = 42328
' WRN_QueryMissingAsClauseinVarDecl = 42329 ' unused in Roslyn.
' WRN_LiftUsingVariableInLambda1 = 42330 ' unused in Roslyn.
' WRN_LiftUsingVariableInQuery1 = 42331 ' unused in Roslyn.
WRN_AmbiguousCastConversion2 = 42332 '// substitutes into 42016
WRN_VarianceDeclarationAmbiguous3 = 42333
WRN_ArrayInitNoTypeObjectAssumed = 42334
WRN_TypeInferenceAssumed3 = 42335
WRN_VarianceConversionFailedOut6 = 42336 '// substitutes into 42016
WRN_VarianceConversionFailedIn6 = 42337 '// substitutes into 42016
WRN_VarianceIEnumerableSuggestion3 = 42338 '// substitutes into 42016
WRN_VarianceConversionFailedTryOut4 = 42339 '// substitutes into 42016
WRN_VarianceConversionFailedTryIn4 = 42340 '// substitutes into 42016
WRN_IfNoTypeObjectAssumed = 42341
WRN_IfTooManyTypesObjectAssumed = 42342
WRN_ArrayInitTooManyTypesObjectAssumed = 42343
WRN_LambdaNoTypeObjectAssumed = 42344
WRN_LambdaTooManyTypesObjectAssumed = 42345
WRN_MissingAsClauseinVarDecl = 42346
WRN_MissingAsClauseinFunction = 42347
WRN_MissingAsClauseinProperty = 42348
WRN_ObsoleteIdentityDirectCastForValueType = 42349
WRN_ImplicitConversion2 = 42350 ' // substitutes into 42016
WRN_MutableStructureInUsing = 42351
WRN_MutableGenericStructureInUsing = 42352
WRN_DefAsgNoRetValFuncVal1 = 42353
WRN_DefAsgNoRetValOpVal1 = 42354
WRN_DefAsgNoRetValPropVal1 = 42355
WRN_AsyncLacksAwaits = 42356
WRN_AsyncSubCouldBeFunction = 42357
WRN_UnobservedAwaitableExpression = 42358
WRN_UnobservedAwaitableDelegate = 42359
WRN_PrefixAndXmlnsLocalName = 42360
WRN_UseValueForXmlExpression3 = 42361 ' Replaces ERR_UseValueForXmlExpression3
'WRN_PDBConstantStringValueTooLong = 42363 we gave up on this warning. See comments in commonCompilation.Emit()
WRN_ReturnTypeAttributeOnWriteOnlyProperty = 42364
ERR_UnmanagedCallersOnlyNotSupported = 42365
WRN_InvalidVersionFormat = 42366
WRN_MainIgnored = 42367
WRN_EmptyPrefixAndXmlnsLocalName = 42368
WRN_DefAsgNoRetValWinRtEventVal1 = 42369
WRN_AssemblyAttributeFromModuleIsOverridden = 42370
WRN_RefCultureMismatch = 42371
WRN_ConflictingMachineAssembly = 42372
WRN_PdbLocalNameTooLong = 42373
WRN_PdbUsingNameTooLong = 42374
WRN_XMLDocCrefToTypeParameter = 42375
WRN_AnalyzerCannotBeCreated = 42376
WRN_NoAnalyzerInAssembly = 42377
WRN_UnableToLoadAnalyzer = 42378
WRN_AttributeIgnoredWhenPublicSigning = 42379
WRN_Experimental = 42380
WRN_AttributeNotSupportedInVB = 42381
ERR_MultipleAnalyzerConfigsInSameDir = 42500
WRN_GeneratorFailedDuringInitialization = 42501
WRN_GeneratorFailedDuringGeneration = 42502
WRN_AnalyzerReferencesFramework = 42503
WRN_CallerArgumentExpressionAttributeSelfReferential = 42504
WRN_CallerArgumentExpressionAttributeHasInvalidParameterName = 42505
' // AVAILABLE 42600 - 49998
ERRWRN_NextAvailable = 42600
'// HIDDENS AND INFOS BEGIN HERE
HDN_UnusedImportClause = 50000
HDN_UnusedImportStatement = 50001
INF_UnableToLoadSomeTypesInAnalyzer = 50002
' // AVAILABLE 50003 - 54999
' Adding diagnostic arguments from resx file
IDS_ProjectSettingsLocationName = 56000
IDS_FunctionReturnType = 56001
IDS_TheSystemCannotFindThePathSpecified = 56002
' available: 56003
IDS_MSG_ADDMODULE = 56004
IDS_MSG_ADDLINKREFERENCE = 56005
IDS_MSG_ADDREFERENCE = 56006
IDS_LogoLine1 = 56007
IDS_LogoLine2 = 56008
IDS_VBCHelp = 56009
IDS_LangVersions = 56010
IDS_ToolName = 56011
ERR_StdInOptionProvidedButConsoleInputIsNotRedirected = 56032
' Feature codes
FEATURE_AutoProperties
FEATURE_LineContinuation
FEATURE_StatementLambdas
FEATURE_CoContraVariance
FEATURE_CollectionInitializers
FEATURE_SubLambdas
FEATURE_ArrayLiterals
FEATURE_AsyncExpressions
FEATURE_Iterators
FEATURE_GlobalNamespace
FEATURE_NullPropagatingOperator
FEATURE_NameOfExpressions
FEATURE_ReadonlyAutoProperties
FEATURE_RegionsEverywhere
FEATURE_MultilineStringLiterals
FEATURE_CObjInAttributeArguments
FEATURE_LineContinuationComments
FEATURE_TypeOfIsNot
FEATURE_YearFirstDateLiterals
FEATURE_WarningDirectives
FEATURE_PartialModules
FEATURE_PartialInterfaces
FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite
FEATURE_DigitSeparators
FEATURE_BinaryLiterals
FEATURE_Tuples
FEATURE_LeadingDigitSeparator
FEATURE_PrivateProtected
FEATURE_InterpolatedStrings
FEATURE_UnconstrainedTypeParameterInConditional
FEATURE_CommentsAfterLineContinuation
FEATURE_InitOnlySettersUsage
FEATURE_CallerArgumentExpression
End Enum
End Namespace
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/TypeStyle/UseVarPreference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CSharp.CodeStyle.TypeStyle
{
[Flags]
internal enum UseVarPreference
{
None = 0,
ForBuiltInTypes = 1 << 0,
WhenTypeIsApparent = 1 << 1,
Elsewhere = 1 << 2,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle
{
[Flags]
internal enum UseVarPreference
{
None = 0,
ForBuiltInTypes = 1 << 0,
WhenTypeIsApparent = 1 << 1,
Elsewhere = 1 << 2,
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/EditorFeatures/Core/Implementation/SplitComment/SplitCommentOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Implementation.SplitComment
{
internal class SplitCommentOptions
{
public static PerLanguageOption2<bool> Enabled =
new PerLanguageOption2<bool>(nameof(SplitCommentOptions), nameof(Enabled), defaultValue: true,
storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitComments"));
}
[ExportOptionProvider, Shared]
internal class SplitCommentOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SplitCommentOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
SplitCommentOptions.Enabled);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Implementation.SplitComment
{
internal class SplitCommentOptions
{
public static PerLanguageOption2<bool> Enabled =
new PerLanguageOption2<bool>(nameof(SplitCommentOptions), nameof(Enabled), defaultValue: true,
storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitComments"));
}
[ExportOptionProvider, Shared]
internal class SplitCommentOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SplitCommentOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
SplitCommentOptions.Enabled);
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/VisualBasic/Portable/BraceCompletion/InterpolationBraceCompletionService.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
Imports Microsoft.CodeAnalysis.BraceCompletion
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic
<Export(LanguageNames.VisualBasic, GetType(IBraceCompletionService)), [Shared]>
Friend Class InterpolationBraceCompletionService
Inherits AbstractBraceCompletionService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
MyBase.New()
End Sub
Protected Overrides ReadOnly Property OpeningBrace As Char = CurlyBrace.OpenCharacter
Protected Overrides ReadOnly Property ClosingBrace As Char = CurlyBrace.CloseCharacter
Protected Overrides Function IsValidOpenBraceTokenAtPositionAsync(token As SyntaxToken, position As Integer, document As Document, cancellationToken As CancellationToken) As Task(Of Boolean)
Return Task.FromResult(IsValidOpeningBraceToken(token))
End Function
Public Overrides Function AllowOverTypeAsync(context As BraceCompletionContext, cancellationToken As CancellationToken) As Task(Of Boolean)
Return AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken)
End Function
Public Overrides Async Function CanProvideBraceCompletionAsync(brace As Char, openingPosition As Integer, document As Document, cancellationToken As CancellationToken) As Task(Of Boolean)
Return OpeningBrace = brace And Await IsPositionInInterpolationContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(False)
End Function
Protected Overrides Function IsValidOpeningBraceToken(token As SyntaxToken) As Boolean
Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken) OrElse
(token.IsKind(SyntaxKind.CloseBraceToken) AndAlso token.Parent.IsKind(SyntaxKind.Interpolation))
End Function
Protected Overrides Function IsValidClosingBraceToken(token As SyntaxToken) As Boolean
Return token.IsKind(SyntaxKind.CloseBraceToken)
End Function
Public Shared Async Function IsPositionInInterpolationContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of Boolean)
If position = 0 Then
Return False
End If
' First, check to see if the character to the left of the position is an open curly.
' If it is, we shouldn't complete because the user may be trying to escape a curly.
' E.g. they are trying to type $"{{"
If (Await CouldEscapePreviousOpenBraceAsync("{"c, position, document, cancellationToken).ConfigureAwait(False)) Then
Return False
End If
' Next, check to see if the token we're typing is part of an existing interpolated string.
'
Dim root = Await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim token = root.FindTokenOnRightOfPosition(position)
If Not token.Span.IntersectsWith(position) Then
Return False
End If
Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken) OrElse
(token.IsKind(SyntaxKind.CloseBraceToken) AndAlso token.Parent.IsKind(SyntaxKind.Interpolation))
End Function
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.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.BraceCompletion
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic
<Export(LanguageNames.VisualBasic, GetType(IBraceCompletionService)), [Shared]>
Friend Class InterpolationBraceCompletionService
Inherits AbstractBraceCompletionService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
MyBase.New()
End Sub
Protected Overrides ReadOnly Property OpeningBrace As Char = CurlyBrace.OpenCharacter
Protected Overrides ReadOnly Property ClosingBrace As Char = CurlyBrace.CloseCharacter
Protected Overrides Function IsValidOpenBraceTokenAtPositionAsync(token As SyntaxToken, position As Integer, document As Document, cancellationToken As CancellationToken) As Task(Of Boolean)
Return Task.FromResult(IsValidOpeningBraceToken(token))
End Function
Public Overrides Function AllowOverTypeAsync(context As BraceCompletionContext, cancellationToken As CancellationToken) As Task(Of Boolean)
Return AllowOverTypeWithValidClosingTokenAsync(context, cancellationToken)
End Function
Public Overrides Async Function CanProvideBraceCompletionAsync(brace As Char, openingPosition As Integer, document As Document, cancellationToken As CancellationToken) As Task(Of Boolean)
Return OpeningBrace = brace And Await IsPositionInInterpolationContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(False)
End Function
Protected Overrides Function IsValidOpeningBraceToken(token As SyntaxToken) As Boolean
Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken) OrElse
(token.IsKind(SyntaxKind.CloseBraceToken) AndAlso token.Parent.IsKind(SyntaxKind.Interpolation))
End Function
Protected Overrides Function IsValidClosingBraceToken(token As SyntaxToken) As Boolean
Return token.IsKind(SyntaxKind.CloseBraceToken)
End Function
Public Shared Async Function IsPositionInInterpolationContextAsync(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of Boolean)
If position = 0 Then
Return False
End If
' First, check to see if the character to the left of the position is an open curly.
' If it is, we shouldn't complete because the user may be trying to escape a curly.
' E.g. they are trying to type $"{{"
If (Await CouldEscapePreviousOpenBraceAsync("{"c, position, document, cancellationToken).ConfigureAwait(False)) Then
Return False
End If
' Next, check to see if the token we're typing is part of an existing interpolated string.
'
Dim root = Await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim token = root.FindTokenOnRightOfPosition(position)
If Not token.Span.IntersectsWith(position) Then
Return False
End If
Return token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.InterpolatedStringTextToken) OrElse
(token.IsKind(SyntaxKind.CloseBraceToken) AndAlso token.Parent.IsKind(SyntaxKind.Interpolation))
End Function
End Class
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.Rewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Formatting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression
{
using static ConvertSwitchStatementToExpressionHelpers;
using static SyntaxFactory;
internal sealed partial class ConvertSwitchStatementToExpressionCodeFixProvider
{
private sealed class Rewriter : CSharpSyntaxVisitor<ExpressionSyntax>
{
private readonly bool _isAllThrowStatements;
private ExpressionSyntax _assignmentTargetOpt;
private Rewriter(bool isAllThrowStatements)
=> _isAllThrowStatements = isAllThrowStatements;
public static StatementSyntax Rewrite(
SwitchStatementSyntax switchStatement,
SemanticModel model,
ITypeSymbol declaratorToRemoveTypeOpt,
SyntaxKind nodeToGenerate,
bool shouldMoveNextStatementToSwitchExpression,
bool generateDeclaration)
{
if (switchStatement.ContainsDirectives)
{
// Do not rewrite statements with preprocessor directives
return switchStatement;
}
var rewriter = new Rewriter(isAllThrowStatements: nodeToGenerate == SyntaxKind.ThrowStatement);
// Rewrite the switch statement as a switch expression.
var switchExpression = rewriter.RewriteSwitchStatement(switchStatement, model,
allowMoveNextStatementToSwitchExpression: shouldMoveNextStatementToSwitchExpression);
// Generate the final statement to wrap the switch expression, e.g. a "return" or an assignment.
return rewriter.GetFinalStatement(switchExpression,
switchStatement.SwitchKeyword.LeadingTrivia, declaratorToRemoveTypeOpt, nodeToGenerate, generateDeclaration);
}
private StatementSyntax GetFinalStatement(
ExpressionSyntax switchExpression,
SyntaxTriviaList leadingTrivia,
ITypeSymbol declaratorToRemoveTypeOpt,
SyntaxKind nodeToGenerate,
bool generateDeclaration)
{
switch (nodeToGenerate)
{
case SyntaxKind.ReturnStatement:
return ReturnStatement(
Token(leadingTrivia, SyntaxKind.ReturnKeyword, trailing: default),
switchExpression,
Token(SyntaxKind.SemicolonToken));
case SyntaxKind.ThrowStatement:
return ThrowStatement(
Token(leadingTrivia, SyntaxKind.ThrowKeyword, trailing: default),
switchExpression,
Token(SyntaxKind.SemicolonToken));
}
Debug.Assert(SyntaxFacts.IsAssignmentExpression(nodeToGenerate));
Debug.Assert(_assignmentTargetOpt != null);
return generateDeclaration
? GenerateVariableDeclaration(switchExpression, declaratorToRemoveTypeOpt)
: GenerateAssignment(switchExpression, nodeToGenerate, leadingTrivia);
}
private ExpressionStatementSyntax GenerateAssignment(ExpressionSyntax switchExpression, SyntaxKind assignmentKind, SyntaxTriviaList leadingTrivia)
{
Debug.Assert(_assignmentTargetOpt != null);
return ExpressionStatement(
AssignmentExpression(assignmentKind,
left: _assignmentTargetOpt,
right: switchExpression))
.WithLeadingTrivia(leadingTrivia);
}
private StatementSyntax GenerateVariableDeclaration(ExpressionSyntax switchExpression, ITypeSymbol declaratorToRemoveTypeOpt)
{
Debug.Assert(_assignmentTargetOpt is IdentifierNameSyntax);
// There is a probability that we cannot use var if the declaration type is a reference type or nullable type.
// In these cases, we generate the explicit type for now and decide later whether or not to use var.
var cannotUseVar = declaratorToRemoveTypeOpt != null && (declaratorToRemoveTypeOpt.IsReferenceType || declaratorToRemoveTypeOpt.IsNullable());
var type = cannotUseVar ? declaratorToRemoveTypeOpt.GenerateTypeSyntax() : IdentifierName("var");
return LocalDeclarationStatement(
VariableDeclaration(
type,
variables: SingletonSeparatedList(
VariableDeclarator(
identifier: ((IdentifierNameSyntax)_assignmentTargetOpt).Identifier,
argumentList: null,
initializer: EqualsValueClause(switchExpression)))));
}
private SwitchExpressionArmSyntax GetSwitchExpressionArm(SwitchSectionSyntax node)
{
return SwitchExpressionArm(
pattern: GetPattern(node.Labels, out var whenClauseOpt),
whenClause: whenClauseOpt,
expression: RewriteStatements(node.Statements));
}
private static PatternSyntax GetPattern(SyntaxList<SwitchLabelSyntax> switchLabels, out WhenClauseSyntax whenClauseOpt)
{
if (switchLabels.Count == 1)
return GetPattern(switchLabels[0], out whenClauseOpt);
if (switchLabels.Any(label => IsDefaultSwitchLabel(label)))
{
// original group had a catch-all label. just convert to a discard _ to indicate the same.
whenClauseOpt = null;
return DiscardPattern();
}
// Multiple labels, and no catch-all merge them using an 'or' pattern.
var totalPattern = GetPattern(switchLabels[0], out var whenClauseUnused);
Debug.Assert(whenClauseUnused == null, "We should not have offered to convert multiple cases if any have a when clause");
for (var i = 1; i < switchLabels.Count; i++)
{
var nextPatternPart = GetPattern(switchLabels[i], out whenClauseUnused);
Debug.Assert(whenClauseUnused == null, "We should not have offered to convert multiple cases if any have a when clause");
totalPattern = BinaryPattern(SyntaxKind.OrPattern, totalPattern.Parenthesize(), nextPatternPart.Parenthesize());
}
whenClauseOpt = null;
return totalPattern;
}
private static PatternSyntax GetPattern(SwitchLabelSyntax switchLabel, out WhenClauseSyntax whenClauseOpt)
{
switch (switchLabel.Kind())
{
case SyntaxKind.CasePatternSwitchLabel:
var node = (CasePatternSwitchLabelSyntax)switchLabel;
whenClauseOpt = node.WhenClause;
return node.Pattern;
case SyntaxKind.CaseSwitchLabel:
whenClauseOpt = null;
return ConstantPattern(((CaseSwitchLabelSyntax)switchLabel).Value);
case SyntaxKind.DefaultSwitchLabel:
whenClauseOpt = null;
return DiscardPattern();
case var value:
throw ExceptionUtilities.UnexpectedValue(value);
}
}
public override ExpressionSyntax VisitAssignmentExpression(AssignmentExpressionSyntax node)
{
_assignmentTargetOpt ??= node.Left;
return node.Right;
}
private ExpressionSyntax RewriteStatements(SyntaxList<StatementSyntax> statements)
{
Debug.Assert(statements.Count == 1 || statements.Count == 2);
Debug.Assert(!statements[0].IsKind(SyntaxKind.BreakStatement));
return Visit(statements[0]);
}
public override ExpressionSyntax VisitSwitchStatement(SwitchStatementSyntax node)
=> RewriteSwitchStatement(node, null);
private ExpressionSyntax RewriteSwitchStatement(SwitchStatementSyntax node, SemanticModel model, bool allowMoveNextStatementToSwitchExpression = true)
{
var switchArms = node.Sections
// The default label must come last in the switch expression.
.OrderBy(section => section.Labels.Any(label => IsDefaultSwitchLabel(label)))
.Select(s =>
(tokensForLeadingTrivia: new[] { s.Labels[0].GetFirstToken(), s.Labels[0].GetLastToken() },
tokensForTrailingTrivia: new[] { s.Statements[0].GetFirstToken(), s.Statements[0].GetLastToken() },
armExpression: GetSwitchExpressionArm(s)))
.ToList();
if (allowMoveNextStatementToSwitchExpression)
{
var nextStatement = node.GetNextStatement();
if (nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement))
{
switchArms.Add(
(tokensForLeadingTrivia: new[] { nextStatement.GetFirstToken() },
tokensForTrailingTrivia: new[] { nextStatement.GetLastToken() },
SwitchExpressionArm(DiscardPattern(), Visit(nextStatement))));
}
}
// add explicit cast if necessary
var switchStatement = AddCastIfNecessary(model, node);
return SwitchExpression(
switchStatement.Expression.Parenthesize(),
Token(leading: default, SyntaxKind.SwitchKeyword, node.CloseParenToken.TrailingTrivia),
Token(leading: default, SyntaxKind.OpenBraceToken, node.OpenBraceToken.TrailingTrivia),
SeparatedList(
switchArms.Select(t => t.armExpression.WithLeadingTrivia(t.tokensForLeadingTrivia.GetTrivia().FilterComments(addElasticMarker: false))),
switchArms.Select(t => Token(SyntaxKind.CommaToken).WithTrailingTrivia(t.tokensForTrailingTrivia.GetTrivia().FilterComments(addElasticMarker: true)))),
Token(SyntaxKind.CloseBraceToken));
}
private static SwitchStatementSyntax AddCastIfNecessary(SemanticModel model, SwitchStatementSyntax node)
{
// If the swith statement expression is being implicitly converted then we need to explicitly cast the expression
// before rewriting as a switch expression
var expressionType = model.GetSymbolInfo(node.Expression).Symbol.GetSymbolType();
var expressionConvertedType = model.GetTypeInfo(node.Expression).ConvertedType;
if (expressionConvertedType != null &&
!SymbolEqualityComparer.Default.Equals(expressionConvertedType, expressionType))
{
return node.Update(node.SwitchKeyword, node.OpenParenToken,
node.Expression.Cast(expressionConvertedType).WithAdditionalAnnotations(Formatter.Annotation),
node.CloseParenToken, node.OpenBraceToken,
node.Sections, node.CloseBraceToken);
}
return node;
}
public override ExpressionSyntax VisitReturnStatement(ReturnStatementSyntax node)
{
Debug.Assert(node.Expression != null);
return node.Expression;
}
public override ExpressionSyntax VisitThrowStatement(ThrowStatementSyntax node)
{
Debug.Assert(node.Expression != null);
// If this is an all-throw switch statement, we return the expression rather than
// creating a throw expression so we can wrap the switch expression inside a throw expression.
return _isAllThrowStatements ? node.Expression : ThrowExpression(node.Expression);
}
public override ExpressionSyntax VisitExpressionStatement(ExpressionStatementSyntax node)
=> Visit(node.Expression);
public override ExpressionSyntax DefaultVisit(SyntaxNode node)
=> 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.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Formatting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression
{
using static ConvertSwitchStatementToExpressionHelpers;
using static SyntaxFactory;
internal sealed partial class ConvertSwitchStatementToExpressionCodeFixProvider
{
private sealed class Rewriter : CSharpSyntaxVisitor<ExpressionSyntax>
{
private readonly bool _isAllThrowStatements;
private ExpressionSyntax _assignmentTargetOpt;
private Rewriter(bool isAllThrowStatements)
=> _isAllThrowStatements = isAllThrowStatements;
public static StatementSyntax Rewrite(
SwitchStatementSyntax switchStatement,
SemanticModel model,
ITypeSymbol declaratorToRemoveTypeOpt,
SyntaxKind nodeToGenerate,
bool shouldMoveNextStatementToSwitchExpression,
bool generateDeclaration)
{
if (switchStatement.ContainsDirectives)
{
// Do not rewrite statements with preprocessor directives
return switchStatement;
}
var rewriter = new Rewriter(isAllThrowStatements: nodeToGenerate == SyntaxKind.ThrowStatement);
// Rewrite the switch statement as a switch expression.
var switchExpression = rewriter.RewriteSwitchStatement(switchStatement, model,
allowMoveNextStatementToSwitchExpression: shouldMoveNextStatementToSwitchExpression);
// Generate the final statement to wrap the switch expression, e.g. a "return" or an assignment.
return rewriter.GetFinalStatement(switchExpression,
switchStatement.SwitchKeyword.LeadingTrivia, declaratorToRemoveTypeOpt, nodeToGenerate, generateDeclaration);
}
private StatementSyntax GetFinalStatement(
ExpressionSyntax switchExpression,
SyntaxTriviaList leadingTrivia,
ITypeSymbol declaratorToRemoveTypeOpt,
SyntaxKind nodeToGenerate,
bool generateDeclaration)
{
switch (nodeToGenerate)
{
case SyntaxKind.ReturnStatement:
return ReturnStatement(
Token(leadingTrivia, SyntaxKind.ReturnKeyword, trailing: default),
switchExpression,
Token(SyntaxKind.SemicolonToken));
case SyntaxKind.ThrowStatement:
return ThrowStatement(
Token(leadingTrivia, SyntaxKind.ThrowKeyword, trailing: default),
switchExpression,
Token(SyntaxKind.SemicolonToken));
}
Debug.Assert(SyntaxFacts.IsAssignmentExpression(nodeToGenerate));
Debug.Assert(_assignmentTargetOpt != null);
return generateDeclaration
? GenerateVariableDeclaration(switchExpression, declaratorToRemoveTypeOpt)
: GenerateAssignment(switchExpression, nodeToGenerate, leadingTrivia);
}
private ExpressionStatementSyntax GenerateAssignment(ExpressionSyntax switchExpression, SyntaxKind assignmentKind, SyntaxTriviaList leadingTrivia)
{
Debug.Assert(_assignmentTargetOpt != null);
return ExpressionStatement(
AssignmentExpression(assignmentKind,
left: _assignmentTargetOpt,
right: switchExpression))
.WithLeadingTrivia(leadingTrivia);
}
private StatementSyntax GenerateVariableDeclaration(ExpressionSyntax switchExpression, ITypeSymbol declaratorToRemoveTypeOpt)
{
Debug.Assert(_assignmentTargetOpt is IdentifierNameSyntax);
// There is a probability that we cannot use var if the declaration type is a reference type or nullable type.
// In these cases, we generate the explicit type for now and decide later whether or not to use var.
var cannotUseVar = declaratorToRemoveTypeOpt != null && (declaratorToRemoveTypeOpt.IsReferenceType || declaratorToRemoveTypeOpt.IsNullable());
var type = cannotUseVar ? declaratorToRemoveTypeOpt.GenerateTypeSyntax() : IdentifierName("var");
return LocalDeclarationStatement(
VariableDeclaration(
type,
variables: SingletonSeparatedList(
VariableDeclarator(
identifier: ((IdentifierNameSyntax)_assignmentTargetOpt).Identifier,
argumentList: null,
initializer: EqualsValueClause(switchExpression)))));
}
private SwitchExpressionArmSyntax GetSwitchExpressionArm(SwitchSectionSyntax node)
{
return SwitchExpressionArm(
pattern: GetPattern(node.Labels, out var whenClauseOpt),
whenClause: whenClauseOpt,
expression: RewriteStatements(node.Statements));
}
private static PatternSyntax GetPattern(SyntaxList<SwitchLabelSyntax> switchLabels, out WhenClauseSyntax whenClauseOpt)
{
if (switchLabels.Count == 1)
return GetPattern(switchLabels[0], out whenClauseOpt);
if (switchLabels.Any(label => IsDefaultSwitchLabel(label)))
{
// original group had a catch-all label. just convert to a discard _ to indicate the same.
whenClauseOpt = null;
return DiscardPattern();
}
// Multiple labels, and no catch-all merge them using an 'or' pattern.
var totalPattern = GetPattern(switchLabels[0], out var whenClauseUnused);
Debug.Assert(whenClauseUnused == null, "We should not have offered to convert multiple cases if any have a when clause");
for (var i = 1; i < switchLabels.Count; i++)
{
var nextPatternPart = GetPattern(switchLabels[i], out whenClauseUnused);
Debug.Assert(whenClauseUnused == null, "We should not have offered to convert multiple cases if any have a when clause");
totalPattern = BinaryPattern(SyntaxKind.OrPattern, totalPattern.Parenthesize(), nextPatternPart.Parenthesize());
}
whenClauseOpt = null;
return totalPattern;
}
private static PatternSyntax GetPattern(SwitchLabelSyntax switchLabel, out WhenClauseSyntax whenClauseOpt)
{
switch (switchLabel.Kind())
{
case SyntaxKind.CasePatternSwitchLabel:
var node = (CasePatternSwitchLabelSyntax)switchLabel;
whenClauseOpt = node.WhenClause;
return node.Pattern;
case SyntaxKind.CaseSwitchLabel:
whenClauseOpt = null;
return ConstantPattern(((CaseSwitchLabelSyntax)switchLabel).Value);
case SyntaxKind.DefaultSwitchLabel:
whenClauseOpt = null;
return DiscardPattern();
case var value:
throw ExceptionUtilities.UnexpectedValue(value);
}
}
public override ExpressionSyntax VisitAssignmentExpression(AssignmentExpressionSyntax node)
{
_assignmentTargetOpt ??= node.Left;
return node.Right;
}
private ExpressionSyntax RewriteStatements(SyntaxList<StatementSyntax> statements)
{
Debug.Assert(statements.Count == 1 || statements.Count == 2);
Debug.Assert(!statements[0].IsKind(SyntaxKind.BreakStatement));
return Visit(statements[0]);
}
public override ExpressionSyntax VisitSwitchStatement(SwitchStatementSyntax node)
=> RewriteSwitchStatement(node, null);
private ExpressionSyntax RewriteSwitchStatement(SwitchStatementSyntax node, SemanticModel model, bool allowMoveNextStatementToSwitchExpression = true)
{
var switchArms = node.Sections
// The default label must come last in the switch expression.
.OrderBy(section => section.Labels.Any(label => IsDefaultSwitchLabel(label)))
.Select(s =>
(tokensForLeadingTrivia: new[] { s.Labels[0].GetFirstToken(), s.Labels[0].GetLastToken() },
tokensForTrailingTrivia: new[] { s.Statements[0].GetFirstToken(), s.Statements[0].GetLastToken() },
armExpression: GetSwitchExpressionArm(s)))
.ToList();
if (allowMoveNextStatementToSwitchExpression)
{
var nextStatement = node.GetNextStatement();
if (nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement))
{
switchArms.Add(
(tokensForLeadingTrivia: new[] { nextStatement.GetFirstToken() },
tokensForTrailingTrivia: new[] { nextStatement.GetLastToken() },
SwitchExpressionArm(DiscardPattern(), Visit(nextStatement))));
}
}
// add explicit cast if necessary
var switchStatement = AddCastIfNecessary(model, node);
return SwitchExpression(
switchStatement.Expression.Parenthesize(),
Token(leading: default, SyntaxKind.SwitchKeyword, node.CloseParenToken.TrailingTrivia),
Token(leading: default, SyntaxKind.OpenBraceToken, node.OpenBraceToken.TrailingTrivia),
SeparatedList(
switchArms.Select(t => t.armExpression.WithLeadingTrivia(t.tokensForLeadingTrivia.GetTrivia().FilterComments(addElasticMarker: false))),
switchArms.Select(t => Token(SyntaxKind.CommaToken).WithTrailingTrivia(t.tokensForTrailingTrivia.GetTrivia().FilterComments(addElasticMarker: true)))),
Token(SyntaxKind.CloseBraceToken));
}
private static SwitchStatementSyntax AddCastIfNecessary(SemanticModel model, SwitchStatementSyntax node)
{
// If the swith statement expression is being implicitly converted then we need to explicitly cast the expression
// before rewriting as a switch expression
var expressionType = model.GetSymbolInfo(node.Expression).Symbol.GetSymbolType();
var expressionConvertedType = model.GetTypeInfo(node.Expression).ConvertedType;
if (expressionConvertedType != null &&
!SymbolEqualityComparer.Default.Equals(expressionConvertedType, expressionType))
{
return node.Update(node.SwitchKeyword, node.OpenParenToken,
node.Expression.Cast(expressionConvertedType).WithAdditionalAnnotations(Formatter.Annotation),
node.CloseParenToken, node.OpenBraceToken,
node.Sections, node.CloseBraceToken);
}
return node;
}
public override ExpressionSyntax VisitReturnStatement(ReturnStatementSyntax node)
{
Debug.Assert(node.Expression != null);
return node.Expression;
}
public override ExpressionSyntax VisitThrowStatement(ThrowStatementSyntax node)
{
Debug.Assert(node.Expression != null);
// If this is an all-throw switch statement, we return the expression rather than
// creating a throw expression so we can wrap the switch expression inside a throw expression.
return _isAllThrowStatements ? node.Expression : ThrowExpression(node.Expression);
}
public override ExpressionSyntax VisitExpressionStatement(ExpressionStatementSyntax node)
=> Visit(node.Expression);
public override ExpressionSyntax DefaultVisit(SyntaxNode node)
=> throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/VisualStudio/Core/Def/ValueTracking/ValueTrackingRoot.xaml | <UserControl x:Class="Microsoft.VisualStudio.LanguageServices.ValueTracking.ValueTrackingRoot"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Microsoft.VisualStudio.LanguageServices.ValueTracking"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0"
Resources="{StaticResource {x:Static vsshell:VsResourceKeys.ThemedDialogDefaultStylesKey}}">
<Grid x:Name="RootGrid">
<TextBlock Text="{Binding EmptyText}" x:Name="EmptyTextMessage"/>
</Grid>
</UserControl>
| <UserControl x:Class="Microsoft.VisualStudio.LanguageServices.ValueTracking.ValueTrackingRoot"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Microsoft.VisualStudio.LanguageServices.ValueTracking"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0"
Resources="{StaticResource {x:Static vsshell:VsResourceKeys.ThemedDialogDefaultStylesKey}}">
<Grid x:Name="RootGrid">
<TextBlock Text="{Binding EmptyText}" x:Name="EmptyTextMessage"/>
</Grid>
</UserControl>
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/Core/Portable/Compilation/EmitResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// The result of the Compilation.Emit method.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
public class EmitResult
{
/// <summary>
/// True if the compilation successfully produced an executable.
/// If false then the diagnostics should include at least one error diagnostic
/// indicating the cause of the failure.
/// </summary>
public bool Success { get; }
/// <summary>
/// A list of all the diagnostics associated with compilations. This include parse errors, declaration errors,
/// compilation errors, and emitting errors.
/// </summary>
public ImmutableArray<Diagnostic> Diagnostics { get; }
internal EmitResult(bool success, ImmutableArray<Diagnostic> diagnostics)
{
Success = success;
Diagnostics = diagnostics;
}
protected virtual string GetDebuggerDisplay()
{
string result = "Success = " + (Success ? "true" : "false");
if (Diagnostics != null)
{
result += ", Diagnostics.Count = " + Diagnostics.Length;
}
else
{
result += ", Diagnostics = null";
}
return result;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// The result of the Compilation.Emit method.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
public class EmitResult
{
/// <summary>
/// True if the compilation successfully produced an executable.
/// If false then the diagnostics should include at least one error diagnostic
/// indicating the cause of the failure.
/// </summary>
public bool Success { get; }
/// <summary>
/// A list of all the diagnostics associated with compilations. This include parse errors, declaration errors,
/// compilation errors, and emitting errors.
/// </summary>
public ImmutableArray<Diagnostic> Diagnostics { get; }
internal EmitResult(bool success, ImmutableArray<Diagnostic> diagnostics)
{
Success = success;
Diagnostics = diagnostics;
}
protected virtual string GetDebuggerDisplay()
{
string result = "Success = " + (Success ? "true" : "false");
if (Diagnostics != null)
{
result += ", Diagnostics.Count = " + Diagnostics.Length;
}
else
{
result += ", Diagnostics = null";
}
return result;
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance();
var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node);
ConstantValue? resultConstant = null;
bool isResultConstant = true;
if (node.Contents.Count == 0)
{
resultConstant = ConstantValue.Create(string.Empty);
}
else
{
var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node);
foreach (var content in node.Contents)
{
switch (content.Kind())
{
case SyntaxKind.Interpolation:
{
var interpolation = (InterpolationSyntax)content;
var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue);
// We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering,
// when we perform overload resolution, to report a problem. So we do that check by calling
// GenerateConversionForAssignment with objectType. However we want to preserve the original expression's
// natural type so that overload resolution may select a specialized implementation of string.Format,
// so we discard the result of that call and only preserve its diagnostics.
BoundExpression? alignment = null;
BoundLiteral? format = null;
if (interpolation.AlignmentClause != null)
{
alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics);
var alignmentConstant = alignment.ConstantValue;
if (alignmentConstant != null && !alignmentConstant.IsBad)
{
const int magnitudeLimit = 32767;
// check that the magnitude of the alignment is "in range".
int alignmentValue = alignmentConstant.Int32Value;
// We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value.
alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue;
if (alignmentValue < -magnitudeLimit)
{
diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit);
}
}
else if (!alignment.HasErrors)
{
diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location);
}
}
if (interpolation.FormatClause != null)
{
var text = interpolation.FormatClause.FormatStringToken.ValueText;
char lastChar;
bool hasErrors = false;
if (text.Length == 0)
{
diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location);
hasErrors = true;
}
else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar))
{
diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location);
hasErrors = true;
}
format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors);
}
builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false));
if (!isResultConstant ||
value.ConstantValue == null ||
!(interpolation is { FormatClause: null, AlignmentClause: null }) ||
!(value.ConstantValue is { IsString: true, IsBad: false }))
{
isResultConstant = false;
continue;
}
resultConstant = (resultConstant is null)
? value.ConstantValue
: FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue);
continue;
}
case SyntaxKind.InterpolatedStringText:
{
var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText;
builder.Add(new BoundLiteral(content, ConstantValue.Create(text, SpecialType.System_String), stringType));
if (isResultConstant)
{
var constantVal = ConstantValue.Create(ConstantValueUtils.UnescapeInterpolatedStringLiteral(text), SpecialType.System_String);
resultConstant = (resultConstant is null)
? constantVal
: FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantVal);
}
continue;
}
default:
throw ExceptionUtilities.UnexpectedValue(content.Kind());
}
}
if (!isResultConstant)
{
resultConstant = null;
}
}
Debug.Assert(isResultConstant == (resultConstant != null));
return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType);
}
private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics)
{
// We have 4 possible lowering strategies, dependent on the contents of the string, in this order:
// 1. The string is a constant value. We can just use the final value.
// 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a
// params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and
// make no intermediate allocations.
// 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression.
// The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any
// awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation
// hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for
// the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected.
// We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we
// cannot put a try/finally inside a filter block.
// 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single
// call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this
// call will need to allocate a param array.
// 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await
// expression. This is turned into a call to string.Format.
//
// We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being
// able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering.
if (unconvertedInterpolatedString.ConstantValue is not null)
{
// Case 1
Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String }));
return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null);
}
// Case 2. Attempt to see if all parts are strings.
if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts))
{
return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null);
}
if (tryBindAsHandlerType(out var result))
{
// Case 3
return result;
}
// The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible
// object.
return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null);
BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data)
=> new BoundInterpolatedString(
unconvertedInterpolatedString.Syntax,
data,
parts,
unconvertedInterpolatedString.ConstantValue,
unconvertedInterpolatedString.Type,
unconvertedInterpolatedString.HasErrors);
bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result)
{
result = null;
if (InExpressionTree || !ValidateInterpolatedStringParts(unconvertedInterpolatedString))
{
return false;
}
var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler);
if (interpolatedStringHandlerType is MissingMetadataTypeSymbol)
{
return false;
}
result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false);
return true;
}
}
private static bool ValidateInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString)
=> !unconvertedInterpolatedString.Parts.ContainsAwaitExpression()
&& unconvertedInterpolatedString.Parts.All(p => p is not BoundStringInsert { Value.Type.TypeKind: TypeKind.Dynamic });
private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray<BoundExpression> parts)
=> parts.All(p => p is BoundLiteral or BoundStringInsert { Value.Type.SpecialType: SpecialType.System_String, Alignment: null, Format: null });
private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator)
{
// Much like BindUnconvertedInterpolatedStringToString above, we only want to use DefaultInterpolatedStringHandler if it's worth it. We therefore
// check for cases 1 and 2: if they are present, we let normal string binary operator binding machinery handle it. Otherwise, we take care of it ourselves.
Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition);
convertedBinaryOperator = null;
if (InExpressionTree)
{
return false;
}
var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler);
if (interpolatedStringHandlerType.IsErrorType())
{
// Can't ever bind to the handler no matter what, so just let the default handling take care of it. Cases 4 and 5 are covered by this.
return false;
}
bool isConstant = true;
var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance();
var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance();
int partsCount = 0;
BoundBinaryOperator? current = binaryOperator;
while (current != null)
{
Debug.Assert(current.IsUnconvertedInterpolatedStringAddition);
stack.Push(current);
isConstant = isConstant && current.Right.ConstantValue is not null;
var rightInterpolatedString = (BoundUnconvertedInterpolatedString)current.Right;
if (!ValidateInterpolatedStringParts(rightInterpolatedString))
{
// Exception to case 3. Delegate to standard binding.
stack.Free();
partsArrayBuilder.Free();
return false;
}
partsCount += rightInterpolatedString.Parts.Length;
partsArrayBuilder.Add(rightInterpolatedString.Parts);
switch (current.Left)
{
case BoundBinaryOperator leftOperator:
current = leftOperator;
continue;
case BoundUnconvertedInterpolatedString interpolatedString:
isConstant = isConstant && interpolatedString.ConstantValue is not null;
if (!ValidateInterpolatedStringParts(interpolatedString))
{
// Exception to case 3. Delegate to standard binding.
stack.Free();
partsArrayBuilder.Free();
return false;
}
partsCount += interpolatedString.Parts.Length;
partsArrayBuilder.Add(interpolatedString.Parts);
current = null;
break;
default:
throw ExceptionUtilities.UnexpectedValue(current.Left.Kind);
}
}
Debug.Assert(partsArrayBuilder.Count == stack.Count + 1);
Debug.Assert(partsArrayBuilder.Count >= 2);
if (isConstant ||
(partsCount <= 4 && partsArrayBuilder.All(static parts => AllInterpolatedStringPartsAreStrings(parts))))
{
// This is case 1 and 2. Let the standard machinery handle it
stack.Free();
partsArrayBuilder.Free();
return false;
}
// Parts were added to the array from right to left, but lexical order is left to right.
partsArrayBuilder.ReverseContents();
// Case 3. Bind as handler.
var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType(
binaryOperator.Syntax,
partsArrayBuilder.ToImmutableAndFree(),
interpolatedStringHandlerType,
diagnostics,
isHandlerConversion: false,
additionalConstructorArguments: default,
additionalConstructorRefKinds: default);
// Now that the parts have been bound, reconstruct the binary operators.
convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(stack, appendCalls, data, binaryOperator.Syntax, diagnostics);
stack.Free();
return true;
}
private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(ArrayBuilder<BoundBinaryOperator> stack, ImmutableArray<ImmutableArray<BoundExpression>> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics)
{
Debug.Assert(appendCalls.Length == stack.Count + 1);
var @string = GetSpecialType(SpecialType.System_String, diagnostics, rootSyntax);
var bottomOperator = stack.Pop();
var result = createBinaryOperator(bottomOperator, createInterpolation(bottomOperator.Left, appendCalls[0]), rightIndex: 1);
for (int i = 2; i < appendCalls.Length; i++)
{
result = createBinaryOperator(stack.Pop(), result, rightIndex: i);
}
return result.Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data));
BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, int rightIndex)
=> new BoundBinaryOperator(
original.Syntax,
BinaryOperatorKind.StringConcatenation,
left,
createInterpolation(original.Right, appendCalls[rightIndex]),
original.ConstantValue,
methodOpt: null,
constrainedToTypeOpt: null,
LookupResultKind.Viable,
originalUserDefinedOperatorsOpt: default,
@string,
original.HasErrors);
static BoundInterpolatedString createInterpolation(BoundExpression expression, ImmutableArray<BoundExpression> parts)
{
Debug.Assert(expression is BoundUnconvertedInterpolatedString);
return new BoundInterpolatedString(
expression.Syntax,
interpolationData: null,
parts,
expression.ConstantValue,
expression.Type,
expression.HasErrors);
}
}
private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType(
BoundExpression unconvertedExpression,
NamedTypeSymbol interpolatedStringHandlerType,
BindingDiagnosticBag diagnostics,
ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default,
ImmutableArray<RefKind> additionalConstructorRefKinds = default)
=> unconvertedExpression switch
{
BoundUnconvertedInterpolatedString interpolatedString => BindUnconvertedInterpolatedStringToHandlerType(
interpolatedString,
interpolatedStringHandlerType,
diagnostics,
isHandlerConversion: true,
additionalConstructorArguments,
additionalConstructorRefKinds),
BoundBinaryOperator binary => BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binary, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds),
_ => throw ExceptionUtilities.UnexpectedValue(unconvertedExpression.Kind)
};
private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType(
BoundUnconvertedInterpolatedString unconvertedInterpolatedString,
NamedTypeSymbol interpolatedStringHandlerType,
BindingDiagnosticBag diagnostics,
bool isHandlerConversion,
ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default,
ImmutableArray<RefKind> additionalConstructorRefKinds = default)
{
var (appendCalls, interpolationData) = BindUnconvertedInterpolatedPartsToHandlerType(
unconvertedInterpolatedString.Syntax,
ImmutableArray.Create(unconvertedInterpolatedString.Parts),
interpolatedStringHandlerType, diagnostics,
isHandlerConversion,
additionalConstructorArguments,
additionalConstructorRefKinds);
Debug.Assert(appendCalls.Length == 1);
return new BoundInterpolatedString(
unconvertedInterpolatedString.Syntax,
interpolationData,
appendCalls[0],
unconvertedInterpolatedString.ConstantValue,
unconvertedInterpolatedString.Type,
unconvertedInterpolatedString.HasErrors);
}
private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(
BoundBinaryOperator binaryOperator,
NamedTypeSymbol interpolatedStringHandlerType,
BindingDiagnosticBag diagnostics,
ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments,
ImmutableArray<RefKind> additionalConstructorRefKinds)
{
Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition);
var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance();
var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance();
BoundBinaryOperator? current = binaryOperator;
while (current != null)
{
stack.Push(current);
partsArrayBuilder.Add(((BoundUnconvertedInterpolatedString)current.Right).Parts);
if (current.Left is BoundBinaryOperator next)
{
current = next;
}
else
{
partsArrayBuilder.Add(((BoundUnconvertedInterpolatedString)current.Left).Parts);
current = null;
}
}
// Parts are added in right to left order, but lexical is left to right.
partsArrayBuilder.ReverseContents();
Debug.Assert(partsArrayBuilder.Count == stack.Count + 1);
Debug.Assert(partsArrayBuilder.Count >= 2);
var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType(
binaryOperator.Syntax,
partsArrayBuilder.ToImmutableAndFree(),
interpolatedStringHandlerType,
diagnostics,
isHandlerConversion: true,
additionalConstructorArguments,
additionalConstructorRefKinds);
var result = UpdateBinaryOperatorWithInterpolatedContents(stack, appendCalls, data, binaryOperator.Syntax, diagnostics);
stack.Free();
return result;
}
private (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType(
SyntaxNode syntax,
ImmutableArray<ImmutableArray<BoundExpression>> partsArray,
NamedTypeSymbol interpolatedStringHandlerType,
BindingDiagnosticBag diagnostics,
bool isHandlerConversion,
ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments,
ImmutableArray<RefKind> additionalConstructorRefKinds)
{
Debug.Assert(additionalConstructorArguments.IsDefault
? additionalConstructorRefKinds.IsDefault
: additionalConstructorArguments.Length == additionalConstructorRefKinds.Length);
additionalConstructorArguments = additionalConstructorArguments.NullToEmpty();
additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty();
ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax);
// We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if
// there are errors we get better diagnostics than "could not convert to object."
var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true };
var (appendCallsArray, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(partsArray, implicitBuilderReceiver, diagnostics);
// Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types
// (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there
// is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components
// are convertible to object if the current langversion is lower than the interpolation feature and we're converting this
// interpolation into an actual string.
bool needToCheckConversionToObject = false;
if (isHandlerConversion)
{
CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics);
}
else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics)
{
needToCheckConversionToObject = true;
}
Debug.Assert(appendCallsArray.Select(a => a.Length).SequenceEqual(partsArray.Select(a => a.Length)));
Debug.Assert(appendCallsArray.All(appendCalls => appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation)));
if (needToCheckConversionToObject)
{
TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, syntax);
BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false);
foreach (var parts in partsArray)
{
foreach (var currentPart in parts)
{
if (currentPart is BoundStringInsert insert)
{
var value = insert.Value;
bool reported = false;
if (value.Type is not null)
{
value = BindToNaturalType(value, conversionDiagnostics);
if (conversionDiagnostics.HasAnyErrors())
{
CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics);
reported = true;
}
}
if (!reported)
{
_ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics);
if (conversionDiagnostics.HasAnyErrors())
{
CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics);
}
}
conversionDiagnostics.Clear();
}
}
}
conversionDiagnostics.Free();
}
var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, syntax);
int constructorArgumentLength = 3 + additionalConstructorArguments.Length;
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength);
var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength);
refKindsBuilder.Add(RefKind.None);
refKindsBuilder.Add(RefKind.None);
refKindsBuilder.AddRange(additionalConstructorRefKinds);
// Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean,
// because we want to track that we're using the type no matter what.
var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, syntax);
var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType);
var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder);
refKindsBuilder.Add(RefKind.Out);
populateArguments(syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder);
BoundExpression constructorCall;
var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies);
var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, outConstructorDiagnostics);
if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable })
{
// MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which
// could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate.
argumentsBuilder.Clear();
// Try again without an out parameter.
populateArguments(syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder);
refKindsBuilder.RemoveLast();
var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics);
BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, nonOutConstructorDiagnostics);
if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable })
{
// We successfully bound the out version, so set all the final data based on that binding
constructorCall = nonOutConstructorCall;
diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics);
outConstructorDiagnostics.Free();
}
else
{
// We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find
// a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed
// for a different reason, that different reason is the one the user will want to know about. If both or neither failed
// because of this error, we'll report everything.
// https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload
// resolution and attempting to determine which method considered was the best to report errors for.
var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false;
var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false;
switch ((nonOutConstructorHasArityError, outConstructorHasArityError))
{
case (true, false):
constructorCall = outConstructorCall;
additionalConstructorArguments = outConstructorAdditionalArguments;
diagnostics.AddRangeAndFree(outConstructorDiagnostics);
nonOutConstructorDiagnostics.Free();
break;
case (false, true):
constructorCall = nonOutConstructorCall;
diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics);
outConstructorDiagnostics.Free();
break;
default:
// For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker,
// but we'll report all diagnostics
constructorCall = nonOutConstructorCall;
diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics);
diagnostics.AddRangeAndFree(outConstructorDiagnostics);
break;
}
}
}
else
{
diagnostics.AddRangeAndFree(outConstructorDiagnostics);
constructorCall = outConstructorCall;
additionalConstructorArguments = outConstructorAdditionalArguments;
}
argumentsBuilder.Free();
refKindsBuilder.Free();
Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression);
if (constructorCall is BoundDynamicObjectCreationExpression)
{
// An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'.
diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name);
}
var interpolationData = new InterpolatedStringHandlerData(
interpolatedStringHandlerType,
constructorCall,
usesBoolReturn,
LocalScopeDepth,
additionalConstructorArguments.NullToEmpty(),
positionInfo,
implicitBuilderReceiver);
return (appendCallsArray, interpolationData);
static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder)
{
// literalLength
argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true });
// formattedCount
argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true });
// Any other arguments from the call site
argumentsBuilder.AddRange(additionalConstructorArguments);
}
}
private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics)
{
ArrayBuilder<BoundExpression>? partsBuilder = null;
var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax);
for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++)
{
var part = unconvertedInterpolatedString.Parts[i];
if (part is BoundStringInsert insert)
{
BoundExpression newValue;
if (insert.Value.Type is null)
{
newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics);
}
else
{
newValue = BindToNaturalType(insert.Value, diagnostics);
_ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics);
}
if (insert.Value != newValue)
{
if (partsBuilder is null)
{
partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length);
partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i);
}
partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false));
}
else
{
partsBuilder?.Add(part);
}
}
else
{
Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } });
partsBuilder?.Add(part);
}
}
return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts;
}
private (ImmutableArray<ImmutableArray<BoundExpression>> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls(
ImmutableArray<ImmutableArray<BoundExpression>> partsArray,
BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver,
BindingDiagnosticBag diagnostics)
{
if (partsArray.IsEmpty && partsArray.All(p => p.IsEmpty))
{
return (ImmutableArray<ImmutableArray<BoundExpression>>.Empty, false, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.Empty, 0, 0);
}
bool? builderPatternExpectsBool = null;
var firstPartsLength = partsArray[0].Length;
var builderAppendCallsArray = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(partsArray.Length);
var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(firstPartsLength);
var positionInfoArray = ArrayBuilder<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.GetInstance(partsArray.Length);
var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(firstPartsLength);
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3);
var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3);
int baseStringLength = 0;
int numFormatHoles = 0;
foreach (var parts in partsArray)
{
foreach (var part in parts)
{
Debug.Assert(part is BoundLiteral or BoundStringInsert);
string methodName;
bool isLiteral;
bool hasAlignment;
bool hasFormat;
if (part is BoundStringInsert insert)
{
methodName = "AppendFormatted";
argumentsBuilder.Add(insert.Value);
parameterNamesAndLocationsBuilder.Add(null);
isLiteral = false;
hasAlignment = false;
hasFormat = false;
if (insert.Alignment is not null)
{
hasAlignment = true;
argumentsBuilder.Add(insert.Alignment);
parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location));
}
if (insert.Format is not null)
{
hasFormat = true;
argumentsBuilder.Add(insert.Format);
parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location));
}
numFormatHoles++;
}
else
{
var boundLiteral = (BoundLiteral)part;
Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString);
var literalText = ConstantValueUtils.UnescapeInterpolatedStringLiteral(boundLiteral.ConstantValue.StringValue);
methodName = "AppendLiteral";
argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type));
isLiteral = true;
hasAlignment = false;
hasFormat = false;
baseStringLength += literalText.Length;
}
var arguments = argumentsBuilder.ToImmutableAndClear();
ImmutableArray<(string, Location)?> parameterNamesAndLocations;
if (parameterNamesAndLocationsBuilder.Count > 1)
{
parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear();
}
else
{
Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null);
parameterNamesAndLocations = default;
parameterNamesAndLocationsBuilder.Clear();
}
var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false);
builderAppendCalls.Add(call);
positionInfo.Add((isLiteral, hasAlignment, hasFormat));
Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true });
// We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that
// void is returned.
if (call is BoundCall { Method: { ReturnType: var returnType } method })
{
bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean;
if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void)
{
// Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'.
diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method);
}
else if (builderPatternExpectsBool == null)
{
builderPatternExpectsBool = methodReturnsBool;
}
else if (builderPatternExpectsBool != methodReturnsBool)
{
// Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'.
var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void);
diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected);
}
}
}
builderAppendCallsArray.Add(builderAppendCalls.ToImmutableAndClear());
positionInfoArray.Add(positionInfo.ToImmutableAndClear());
}
argumentsBuilder.Free();
parameterNamesAndLocationsBuilder.Free();
builderAppendCalls.Free();
positionInfo.Free();
return (builderAppendCallsArray.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfoArray.ToImmutableAndFree(), baseStringLength, numFormatHoles);
}
private BoundExpression BindInterpolatedStringHandlerInMemberCall(
BoundExpression unconvertedString,
ArrayBuilder<BoundExpression> arguments,
ImmutableArray<ParameterSymbol> parameters,
ref MemberAnalysisResult memberAnalysisResult,
int interpolatedStringArgNum,
TypeSymbol? receiverType,
RefKind? receiverRefKind,
uint receiverEscapeScope,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(unconvertedString is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true });
var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum);
Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler);
var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum);
Debug.Assert(interpolatedStringParameter is { Type: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } }
#pragma warning disable format
or
{
IsParams: true,
Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } },
InterpolatedStringHandlerArgumentIndexes.IsEmpty: true
});
#pragma warning restore format
Debug.Assert(!interpolatedStringParameter.IsParams || memberAnalysisResult.Kind == MemberResolutionKind.ApplicableInExpandedForm);
if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError)
{
// The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually.
diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type);
return CreateConversion(
unconvertedString.Syntax,
unconvertedString,
interpolatedStringConversion,
isCast: false,
conversionGroupOpt: null,
wasCompilerGenerated: false,
interpolatedStringParameter.Type,
diagnostics,
hasErrors: true);
}
var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes;
if (handlerParameterIndexes.IsEmpty)
{
// No arguments, fall back to the standard conversion steps.
return CreateConversion(
unconvertedString.Syntax,
unconvertedString,
interpolatedStringConversion,
isCast: false,
conversionGroupOpt: null,
interpolatedStringParameter.IsParams ? ((ArrayTypeSymbol)interpolatedStringParameter.Type).ElementType : interpolatedStringParameter.Type,
diagnostics);
}
Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength,
parameters.Length));
// We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter
ImmutableArray<int> handlerArgumentIndexes;
if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length)
{
// No parameters are missing and no remapped indexes, we can just use the original indexes
handlerArgumentIndexes = handlerParameterIndexes;
}
else
{
// Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter.
var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter);
for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++)
{
int handlerParameter = handlerParameterIndexes[handlerParameterIndex];
Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter);
if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter)
{
handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter;
continue;
}
for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++)
{
// The index in the original parameter list we're looking to match up.
int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex);
// Is the original parameter index of the current argument the parameter index that was specified in the attribute?
if (argumentParameterIndex == handlerParameter)
{
// We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice.
handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex;
}
}
}
handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree();
}
var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length);
var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length);
bool hasErrors = false;
// Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct
// a set of placeholders for overload resolution.
for (int i = 0; i < handlerArgumentIndexes.Length; i++)
{
int argumentIndex = handlerArgumentIndexes[i];
Debug.Assert(argumentIndex != interpolatedStringArgNum);
RefKind refKind;
TypeSymbol placeholderType;
switch (argumentIndex)
{
case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter:
Debug.Assert(receiverRefKind != null && receiverType is not null);
refKind = receiverRefKind.GetValueOrDefault();
placeholderType = receiverType;
break;
case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter:
{
// Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed.
// If it is optional, then they could otherwise not specify the parameter and that's an error
var originalParameterIndex = handlerParameterIndexes[i];
var parameter = parameters[originalParameterIndex];
if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter)))
{
// Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'.
diagnostics.Add(
ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified,
unconvertedString.Syntax.Location,
parameter.Name,
interpolatedStringParameter.Name);
hasErrors = true;
}
refKind = parameter.RefKind;
placeholderType = parameter.Type;
}
break;
default:
{
var originalParameterIndex = handlerParameterIndexes[i];
var parameter = parameters[originalParameterIndex];
if (argumentIndex > interpolatedStringArgNum)
{
// Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'.
diagnostics.Add(
ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString,
arguments[argumentIndex].Syntax.Location,
parameter.Name,
interpolatedStringParameter.Name);
hasErrors = true;
}
refKind = parameter.RefKind;
placeholderType = parameter.Type;
}
break;
}
SyntaxNode placeholderSyntax;
uint valSafeToEscapeScope;
switch (argumentIndex)
{
case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter:
placeholderSyntax = unconvertedString.Syntax;
valSafeToEscapeScope = receiverEscapeScope;
break;
case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter:
placeholderSyntax = unconvertedString.Syntax;
valSafeToEscapeScope = Binder.ExternalScope;
break;
case >= 0:
placeholderSyntax = arguments[argumentIndex].Syntax;
valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth);
break;
default:
throw ExceptionUtilities.UnexpectedValue(argumentIndex);
}
argumentPlaceholdersBuilder.Add(
new BoundInterpolatedStringArgumentPlaceholder(
placeholderSyntax,
argumentIndex,
valSafeToEscapeScope,
placeholderType,
hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter));
// We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors
// about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will
// be a place where refkinds are allowed to differ
argumentRefKindsBuilder.Add(refKind);
}
var interpolatedString = BindUnconvertedInterpolatedExpressionToHandlerType(
unconvertedString,
(NamedTypeSymbol)interpolatedStringParameter.Type,
diagnostics,
additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(),
additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree());
return new BoundConversion(
interpolatedString.Syntax,
interpolatedString,
interpolatedStringConversion,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: false,
conversionGroupOpt: null,
constantValueOpt: null,
interpolatedStringParameter.Type,
hasErrors || interpolatedString.HasErrors);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance();
var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node);
ConstantValue? resultConstant = null;
bool isResultConstant = true;
if (node.Contents.Count == 0)
{
resultConstant = ConstantValue.Create(string.Empty);
}
else
{
var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node);
foreach (var content in node.Contents)
{
switch (content.Kind())
{
case SyntaxKind.Interpolation:
{
var interpolation = (InterpolationSyntax)content;
var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue);
// We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering,
// when we perform overload resolution, to report a problem. So we do that check by calling
// GenerateConversionForAssignment with objectType. However we want to preserve the original expression's
// natural type so that overload resolution may select a specialized implementation of string.Format,
// so we discard the result of that call and only preserve its diagnostics.
BoundExpression? alignment = null;
BoundLiteral? format = null;
if (interpolation.AlignmentClause != null)
{
alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics);
var alignmentConstant = alignment.ConstantValue;
if (alignmentConstant != null && !alignmentConstant.IsBad)
{
const int magnitudeLimit = 32767;
// check that the magnitude of the alignment is "in range".
int alignmentValue = alignmentConstant.Int32Value;
// We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value.
alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue;
if (alignmentValue < -magnitudeLimit)
{
diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit);
}
}
else if (!alignment.HasErrors)
{
diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location);
}
}
if (interpolation.FormatClause != null)
{
var text = interpolation.FormatClause.FormatStringToken.ValueText;
char lastChar;
bool hasErrors = false;
if (text.Length == 0)
{
diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location);
hasErrors = true;
}
else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar))
{
diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location);
hasErrors = true;
}
format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors);
}
builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false));
if (!isResultConstant ||
value.ConstantValue == null ||
!(interpolation is { FormatClause: null, AlignmentClause: null }) ||
!(value.ConstantValue is { IsString: true, IsBad: false }))
{
isResultConstant = false;
continue;
}
resultConstant = (resultConstant is null)
? value.ConstantValue
: FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue);
continue;
}
case SyntaxKind.InterpolatedStringText:
{
var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText;
builder.Add(new BoundLiteral(content, ConstantValue.Create(text, SpecialType.System_String), stringType));
if (isResultConstant)
{
var constantVal = ConstantValue.Create(ConstantValueUtils.UnescapeInterpolatedStringLiteral(text), SpecialType.System_String);
resultConstant = (resultConstant is null)
? constantVal
: FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantVal);
}
continue;
}
default:
throw ExceptionUtilities.UnexpectedValue(content.Kind());
}
}
if (!isResultConstant)
{
resultConstant = null;
}
}
Debug.Assert(isResultConstant == (resultConstant != null));
return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType);
}
private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics)
{
// We have 4 possible lowering strategies, dependent on the contents of the string, in this order:
// 1. The string is a constant value. We can just use the final value.
// 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a
// params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and
// make no intermediate allocations.
// 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression.
// The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any
// awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation
// hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for
// the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected.
// We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we
// cannot put a try/finally inside a filter block.
// 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single
// call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this
// call will need to allocate a param array.
// 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await
// expression. This is turned into a call to string.Format.
//
// We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being
// able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering.
if (unconvertedInterpolatedString.ConstantValue is not null)
{
// Case 1
Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String }));
return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null);
}
// Case 2. Attempt to see if all parts are strings.
if (unconvertedInterpolatedString.Parts.Length <= 4 && AllInterpolatedStringPartsAreStrings(unconvertedInterpolatedString.Parts))
{
return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null);
}
if (tryBindAsHandlerType(out var result))
{
// Case 3
return result;
}
// The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible
// object.
return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null);
BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data)
=> new BoundInterpolatedString(
unconvertedInterpolatedString.Syntax,
data,
parts,
unconvertedInterpolatedString.ConstantValue,
unconvertedInterpolatedString.Type,
unconvertedInterpolatedString.HasErrors);
bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result)
{
result = null;
if (InExpressionTree || !ValidateInterpolatedStringParts(unconvertedInterpolatedString))
{
return false;
}
var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler);
if (interpolatedStringHandlerType is MissingMetadataTypeSymbol)
{
return false;
}
result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false);
return true;
}
}
private static bool ValidateInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString)
=> !unconvertedInterpolatedString.Parts.ContainsAwaitExpression()
&& unconvertedInterpolatedString.Parts.All(p => p is not BoundStringInsert { Value.Type.TypeKind: TypeKind.Dynamic });
private static bool AllInterpolatedStringPartsAreStrings(ImmutableArray<BoundExpression> parts)
=> parts.All(p => p is BoundLiteral or BoundStringInsert { Value.Type.SpecialType: SpecialType.System_String, Alignment: null, Format: null });
private bool TryBindUnconvertedBinaryOperatorToDefaultInterpolatedStringHandler(BoundBinaryOperator binaryOperator, BindingDiagnosticBag diagnostics, [NotNullWhen(true)] out BoundBinaryOperator? convertedBinaryOperator)
{
// Much like BindUnconvertedInterpolatedStringToString above, we only want to use DefaultInterpolatedStringHandler if it's worth it. We therefore
// check for cases 1 and 2: if they are present, we let normal string binary operator binding machinery handle it. Otherwise, we take care of it ourselves.
Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition);
convertedBinaryOperator = null;
if (InExpressionTree)
{
return false;
}
var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler);
if (interpolatedStringHandlerType.IsErrorType())
{
// Can't ever bind to the handler no matter what, so just let the default handling take care of it. Cases 4 and 5 are covered by this.
return false;
}
bool isConstant = true;
var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance();
var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance();
int partsCount = 0;
BoundBinaryOperator? current = binaryOperator;
while (current != null)
{
Debug.Assert(current.IsUnconvertedInterpolatedStringAddition);
stack.Push(current);
isConstant = isConstant && current.Right.ConstantValue is not null;
var rightInterpolatedString = (BoundUnconvertedInterpolatedString)current.Right;
if (!ValidateInterpolatedStringParts(rightInterpolatedString))
{
// Exception to case 3. Delegate to standard binding.
stack.Free();
partsArrayBuilder.Free();
return false;
}
partsCount += rightInterpolatedString.Parts.Length;
partsArrayBuilder.Add(rightInterpolatedString.Parts);
switch (current.Left)
{
case BoundBinaryOperator leftOperator:
current = leftOperator;
continue;
case BoundUnconvertedInterpolatedString interpolatedString:
isConstant = isConstant && interpolatedString.ConstantValue is not null;
if (!ValidateInterpolatedStringParts(interpolatedString))
{
// Exception to case 3. Delegate to standard binding.
stack.Free();
partsArrayBuilder.Free();
return false;
}
partsCount += interpolatedString.Parts.Length;
partsArrayBuilder.Add(interpolatedString.Parts);
current = null;
break;
default:
throw ExceptionUtilities.UnexpectedValue(current.Left.Kind);
}
}
Debug.Assert(partsArrayBuilder.Count == stack.Count + 1);
Debug.Assert(partsArrayBuilder.Count >= 2);
if (isConstant ||
(partsCount <= 4 && partsArrayBuilder.All(static parts => AllInterpolatedStringPartsAreStrings(parts))))
{
// This is case 1 and 2. Let the standard machinery handle it
stack.Free();
partsArrayBuilder.Free();
return false;
}
// Parts were added to the array from right to left, but lexical order is left to right.
partsArrayBuilder.ReverseContents();
// Case 3. Bind as handler.
var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType(
binaryOperator.Syntax,
partsArrayBuilder.ToImmutableAndFree(),
interpolatedStringHandlerType,
diagnostics,
isHandlerConversion: false,
additionalConstructorArguments: default,
additionalConstructorRefKinds: default);
// Now that the parts have been bound, reconstruct the binary operators.
convertedBinaryOperator = UpdateBinaryOperatorWithInterpolatedContents(stack, appendCalls, data, binaryOperator.Syntax, diagnostics);
stack.Free();
return true;
}
private BoundBinaryOperator UpdateBinaryOperatorWithInterpolatedContents(ArrayBuilder<BoundBinaryOperator> stack, ImmutableArray<ImmutableArray<BoundExpression>> appendCalls, InterpolatedStringHandlerData data, SyntaxNode rootSyntax, BindingDiagnosticBag diagnostics)
{
Debug.Assert(appendCalls.Length == stack.Count + 1);
var @string = GetSpecialType(SpecialType.System_String, diagnostics, rootSyntax);
var bottomOperator = stack.Pop();
var result = createBinaryOperator(bottomOperator, createInterpolation(bottomOperator.Left, appendCalls[0]), rightIndex: 1);
for (int i = 2; i < appendCalls.Length; i++)
{
result = createBinaryOperator(stack.Pop(), result, rightIndex: i);
}
return result.Update(BoundBinaryOperator.UncommonData.InterpolatedStringHandlerAddition(data));
BoundBinaryOperator createBinaryOperator(BoundBinaryOperator original, BoundExpression left, int rightIndex)
=> new BoundBinaryOperator(
original.Syntax,
BinaryOperatorKind.StringConcatenation,
left,
createInterpolation(original.Right, appendCalls[rightIndex]),
original.ConstantValue,
methodOpt: null,
constrainedToTypeOpt: null,
LookupResultKind.Viable,
originalUserDefinedOperatorsOpt: default,
@string,
original.HasErrors);
static BoundInterpolatedString createInterpolation(BoundExpression expression, ImmutableArray<BoundExpression> parts)
{
Debug.Assert(expression is BoundUnconvertedInterpolatedString);
return new BoundInterpolatedString(
expression.Syntax,
interpolationData: null,
parts,
expression.ConstantValue,
expression.Type,
expression.HasErrors);
}
}
private BoundExpression BindUnconvertedInterpolatedExpressionToHandlerType(
BoundExpression unconvertedExpression,
NamedTypeSymbol interpolatedStringHandlerType,
BindingDiagnosticBag diagnostics,
ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default,
ImmutableArray<RefKind> additionalConstructorRefKinds = default)
=> unconvertedExpression switch
{
BoundUnconvertedInterpolatedString interpolatedString => BindUnconvertedInterpolatedStringToHandlerType(
interpolatedString,
interpolatedStringHandlerType,
diagnostics,
isHandlerConversion: true,
additionalConstructorArguments,
additionalConstructorRefKinds),
BoundBinaryOperator binary => BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(binary, interpolatedStringHandlerType, diagnostics, additionalConstructorArguments, additionalConstructorRefKinds),
_ => throw ExceptionUtilities.UnexpectedValue(unconvertedExpression.Kind)
};
private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType(
BoundUnconvertedInterpolatedString unconvertedInterpolatedString,
NamedTypeSymbol interpolatedStringHandlerType,
BindingDiagnosticBag diagnostics,
bool isHandlerConversion,
ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default,
ImmutableArray<RefKind> additionalConstructorRefKinds = default)
{
var (appendCalls, interpolationData) = BindUnconvertedInterpolatedPartsToHandlerType(
unconvertedInterpolatedString.Syntax,
ImmutableArray.Create(unconvertedInterpolatedString.Parts),
interpolatedStringHandlerType, diagnostics,
isHandlerConversion,
additionalConstructorArguments,
additionalConstructorRefKinds);
Debug.Assert(appendCalls.Length == 1);
return new BoundInterpolatedString(
unconvertedInterpolatedString.Syntax,
interpolationData,
appendCalls[0],
unconvertedInterpolatedString.ConstantValue,
unconvertedInterpolatedString.Type,
unconvertedInterpolatedString.HasErrors);
}
private BoundBinaryOperator BindUnconvertedBinaryOperatorToInterpolatedStringHandlerType(
BoundBinaryOperator binaryOperator,
NamedTypeSymbol interpolatedStringHandlerType,
BindingDiagnosticBag diagnostics,
ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments,
ImmutableArray<RefKind> additionalConstructorRefKinds)
{
Debug.Assert(binaryOperator.IsUnconvertedInterpolatedStringAddition);
var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance();
var partsArrayBuilder = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance();
BoundBinaryOperator? current = binaryOperator;
while (current != null)
{
stack.Push(current);
partsArrayBuilder.Add(((BoundUnconvertedInterpolatedString)current.Right).Parts);
if (current.Left is BoundBinaryOperator next)
{
current = next;
}
else
{
partsArrayBuilder.Add(((BoundUnconvertedInterpolatedString)current.Left).Parts);
current = null;
}
}
// Parts are added in right to left order, but lexical is left to right.
partsArrayBuilder.ReverseContents();
Debug.Assert(partsArrayBuilder.Count == stack.Count + 1);
Debug.Assert(partsArrayBuilder.Count >= 2);
var (appendCalls, data) = BindUnconvertedInterpolatedPartsToHandlerType(
binaryOperator.Syntax,
partsArrayBuilder.ToImmutableAndFree(),
interpolatedStringHandlerType,
diagnostics,
isHandlerConversion: true,
additionalConstructorArguments,
additionalConstructorRefKinds);
var result = UpdateBinaryOperatorWithInterpolatedContents(stack, appendCalls, data, binaryOperator.Syntax, diagnostics);
stack.Free();
return result;
}
private (ImmutableArray<ImmutableArray<BoundExpression>> AppendCalls, InterpolatedStringHandlerData Data) BindUnconvertedInterpolatedPartsToHandlerType(
SyntaxNode syntax,
ImmutableArray<ImmutableArray<BoundExpression>> partsArray,
NamedTypeSymbol interpolatedStringHandlerType,
BindingDiagnosticBag diagnostics,
bool isHandlerConversion,
ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments,
ImmutableArray<RefKind> additionalConstructorRefKinds)
{
Debug.Assert(additionalConstructorArguments.IsDefault
? additionalConstructorRefKinds.IsDefault
: additionalConstructorArguments.Length == additionalConstructorRefKinds.Length);
additionalConstructorArguments = additionalConstructorArguments.NullToEmpty();
additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty();
ReportUseSite(interpolatedStringHandlerType, diagnostics, syntax);
// We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if
// there are errors we get better diagnostics than "could not convert to object."
var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true };
var (appendCallsArray, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(partsArray, implicitBuilderReceiver, diagnostics);
// Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types
// (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there
// is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components
// are convertible to object if the current langversion is lower than the interpolation feature and we're converting this
// interpolation into an actual string.
bool needToCheckConversionToObject = false;
if (isHandlerConversion)
{
CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics);
}
else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics)
{
needToCheckConversionToObject = true;
}
Debug.Assert(appendCallsArray.Select(a => a.Length).SequenceEqual(partsArray.Select(a => a.Length)));
Debug.Assert(appendCallsArray.All(appendCalls => appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation)));
if (needToCheckConversionToObject)
{
TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, syntax);
BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false);
foreach (var parts in partsArray)
{
foreach (var currentPart in parts)
{
if (currentPart is BoundStringInsert insert)
{
var value = insert.Value;
bool reported = false;
if (value.Type is not null)
{
value = BindToNaturalType(value, conversionDiagnostics);
if (conversionDiagnostics.HasAnyErrors())
{
CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics);
reported = true;
}
}
if (!reported)
{
_ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics);
if (conversionDiagnostics.HasAnyErrors())
{
CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics);
}
}
conversionDiagnostics.Clear();
}
}
}
conversionDiagnostics.Free();
}
var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, syntax);
int constructorArgumentLength = 3 + additionalConstructorArguments.Length;
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength);
var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength);
refKindsBuilder.Add(RefKind.None);
refKindsBuilder.Add(RefKind.None);
refKindsBuilder.AddRange(additionalConstructorRefKinds);
// Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean,
// because we want to track that we're using the type no matter what.
var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, syntax);
var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType);
var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder);
refKindsBuilder.Add(RefKind.Out);
populateArguments(syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder);
BoundExpression constructorCall;
var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies);
var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, outConstructorDiagnostics);
if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable })
{
// MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which
// could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate.
argumentsBuilder.Clear();
// Try again without an out parameter.
populateArguments(syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder);
refKindsBuilder.RemoveLast();
var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics);
BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, syntax, nonOutConstructorDiagnostics);
if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable })
{
// We successfully bound the out version, so set all the final data based on that binding
constructorCall = nonOutConstructorCall;
diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics);
outConstructorDiagnostics.Free();
}
else
{
// We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find
// a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed
// for a different reason, that different reason is the one the user will want to know about. If both or neither failed
// because of this error, we'll report everything.
// https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload
// resolution and attempting to determine which method considered was the best to report errors for.
var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false;
var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false;
switch ((nonOutConstructorHasArityError, outConstructorHasArityError))
{
case (true, false):
constructorCall = outConstructorCall;
additionalConstructorArguments = outConstructorAdditionalArguments;
diagnostics.AddRangeAndFree(outConstructorDiagnostics);
nonOutConstructorDiagnostics.Free();
break;
case (false, true):
constructorCall = nonOutConstructorCall;
diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics);
outConstructorDiagnostics.Free();
break;
default:
// For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker,
// but we'll report all diagnostics
constructorCall = nonOutConstructorCall;
diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics);
diagnostics.AddRangeAndFree(outConstructorDiagnostics);
break;
}
}
}
else
{
diagnostics.AddRangeAndFree(outConstructorDiagnostics);
constructorCall = outConstructorCall;
additionalConstructorArguments = outConstructorAdditionalArguments;
}
argumentsBuilder.Free();
refKindsBuilder.Free();
Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression);
if (constructorCall is BoundDynamicObjectCreationExpression)
{
// An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'.
diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, syntax.Location, interpolatedStringHandlerType.Name);
}
var interpolationData = new InterpolatedStringHandlerData(
interpolatedStringHandlerType,
constructorCall,
usesBoolReturn,
LocalScopeDepth,
additionalConstructorArguments.NullToEmpty(),
positionInfo,
implicitBuilderReceiver);
return (appendCallsArray, interpolationData);
static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder)
{
// literalLength
argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true });
// formattedCount
argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true });
// Any other arguments from the call site
argumentsBuilder.AddRange(additionalConstructorArguments);
}
}
private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics)
{
ArrayBuilder<BoundExpression>? partsBuilder = null;
var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax);
for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++)
{
var part = unconvertedInterpolatedString.Parts[i];
if (part is BoundStringInsert insert)
{
BoundExpression newValue;
if (insert.Value.Type is null)
{
newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics);
}
else
{
newValue = BindToNaturalType(insert.Value, diagnostics);
_ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics);
}
if (insert.Value != newValue)
{
if (partsBuilder is null)
{
partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length);
partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i);
}
partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false));
}
else
{
partsBuilder?.Add(part);
}
}
else
{
Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } });
partsBuilder?.Add(part);
}
}
return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts;
}
private (ImmutableArray<ImmutableArray<BoundExpression>> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls(
ImmutableArray<ImmutableArray<BoundExpression>> partsArray,
BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver,
BindingDiagnosticBag diagnostics)
{
if (partsArray.IsEmpty && partsArray.All(p => p.IsEmpty))
{
return (ImmutableArray<ImmutableArray<BoundExpression>>.Empty, false, ImmutableArray<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.Empty, 0, 0);
}
bool? builderPatternExpectsBool = null;
var firstPartsLength = partsArray[0].Length;
var builderAppendCallsArray = ArrayBuilder<ImmutableArray<BoundExpression>>.GetInstance(partsArray.Length);
var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(firstPartsLength);
var positionInfoArray = ArrayBuilder<ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>>.GetInstance(partsArray.Length);
var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(firstPartsLength);
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3);
var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3);
int baseStringLength = 0;
int numFormatHoles = 0;
foreach (var parts in partsArray)
{
foreach (var part in parts)
{
Debug.Assert(part is BoundLiteral or BoundStringInsert);
string methodName;
bool isLiteral;
bool hasAlignment;
bool hasFormat;
if (part is BoundStringInsert insert)
{
methodName = "AppendFormatted";
argumentsBuilder.Add(insert.Value);
parameterNamesAndLocationsBuilder.Add(null);
isLiteral = false;
hasAlignment = false;
hasFormat = false;
if (insert.Alignment is not null)
{
hasAlignment = true;
argumentsBuilder.Add(insert.Alignment);
parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location));
}
if (insert.Format is not null)
{
hasFormat = true;
argumentsBuilder.Add(insert.Format);
parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location));
}
numFormatHoles++;
}
else
{
var boundLiteral = (BoundLiteral)part;
Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString);
var literalText = ConstantValueUtils.UnescapeInterpolatedStringLiteral(boundLiteral.ConstantValue.StringValue);
methodName = "AppendLiteral";
argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type));
isLiteral = true;
hasAlignment = false;
hasFormat = false;
baseStringLength += literalText.Length;
}
var arguments = argumentsBuilder.ToImmutableAndClear();
ImmutableArray<(string, Location)?> parameterNamesAndLocations;
if (parameterNamesAndLocationsBuilder.Count > 1)
{
parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear();
}
else
{
Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null);
parameterNamesAndLocations = default;
parameterNamesAndLocationsBuilder.Clear();
}
var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false);
builderAppendCalls.Add(call);
positionInfo.Add((isLiteral, hasAlignment, hasFormat));
Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true });
// We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that
// void is returned.
if (call is BoundCall { Method: { ReturnType: var returnType } method })
{
bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean;
if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void)
{
// Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'.
diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method);
}
else if (builderPatternExpectsBool == null)
{
builderPatternExpectsBool = methodReturnsBool;
}
else if (builderPatternExpectsBool != methodReturnsBool)
{
// Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'.
var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void);
diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected);
}
}
}
builderAppendCallsArray.Add(builderAppendCalls.ToImmutableAndClear());
positionInfoArray.Add(positionInfo.ToImmutableAndClear());
}
argumentsBuilder.Free();
parameterNamesAndLocationsBuilder.Free();
builderAppendCalls.Free();
positionInfo.Free();
return (builderAppendCallsArray.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfoArray.ToImmutableAndFree(), baseStringLength, numFormatHoles);
}
private BoundExpression BindInterpolatedStringHandlerInMemberCall(
BoundExpression unconvertedString,
ArrayBuilder<BoundExpression> arguments,
ImmutableArray<ParameterSymbol> parameters,
ref MemberAnalysisResult memberAnalysisResult,
int interpolatedStringArgNum,
TypeSymbol? receiverType,
RefKind? receiverRefKind,
uint receiverEscapeScope,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(unconvertedString is BoundUnconvertedInterpolatedString or BoundBinaryOperator { IsUnconvertedInterpolatedStringAddition: true });
var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum);
Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler);
var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum);
Debug.Assert(interpolatedStringParameter is { Type: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } }
#pragma warning disable format
or
{
IsParams: true,
Type: ArrayTypeSymbol { ElementType: NamedTypeSymbol { IsInterpolatedStringHandlerType: true } },
InterpolatedStringHandlerArgumentIndexes.IsEmpty: true
});
#pragma warning restore format
Debug.Assert(!interpolatedStringParameter.IsParams || memberAnalysisResult.Kind == MemberResolutionKind.ApplicableInExpandedForm);
if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError)
{
// The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually.
diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type);
return CreateConversion(
unconvertedString.Syntax,
unconvertedString,
interpolatedStringConversion,
isCast: false,
conversionGroupOpt: null,
wasCompilerGenerated: false,
interpolatedStringParameter.Type,
diagnostics,
hasErrors: true);
}
var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes;
if (handlerParameterIndexes.IsEmpty)
{
// No arguments, fall back to the standard conversion steps.
return CreateConversion(
unconvertedString.Syntax,
unconvertedString,
interpolatedStringConversion,
isCast: false,
conversionGroupOpt: null,
interpolatedStringParameter.IsParams ? ((ArrayTypeSymbol)interpolatedStringParameter.Type).ElementType : interpolatedStringParameter.Type,
diagnostics);
}
Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength,
parameters.Length));
// We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter
ImmutableArray<int> handlerArgumentIndexes;
if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length)
{
// No parameters are missing and no remapped indexes, we can just use the original indexes
handlerArgumentIndexes = handlerParameterIndexes;
}
else
{
// Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter.
var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter);
for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++)
{
int handlerParameter = handlerParameterIndexes[handlerParameterIndex];
Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter);
if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter)
{
handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter;
continue;
}
for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++)
{
// The index in the original parameter list we're looking to match up.
int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex);
// Is the original parameter index of the current argument the parameter index that was specified in the attribute?
if (argumentParameterIndex == handlerParameter)
{
// We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice.
handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex;
}
}
}
handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree();
}
var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length);
var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length);
bool hasErrors = false;
// Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct
// a set of placeholders for overload resolution.
for (int i = 0; i < handlerArgumentIndexes.Length; i++)
{
int argumentIndex = handlerArgumentIndexes[i];
Debug.Assert(argumentIndex != interpolatedStringArgNum);
RefKind refKind;
TypeSymbol placeholderType;
switch (argumentIndex)
{
case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter:
Debug.Assert(receiverRefKind != null && receiverType is not null);
refKind = receiverRefKind.GetValueOrDefault();
placeholderType = receiverType;
break;
case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter:
{
// Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed.
// If it is optional, then they could otherwise not specify the parameter and that's an error
var originalParameterIndex = handlerParameterIndexes[i];
var parameter = parameters[originalParameterIndex];
if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter)))
{
// Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'.
diagnostics.Add(
ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified,
unconvertedString.Syntax.Location,
parameter.Name,
interpolatedStringParameter.Name);
hasErrors = true;
}
refKind = parameter.RefKind;
placeholderType = parameter.Type;
}
break;
default:
{
var originalParameterIndex = handlerParameterIndexes[i];
var parameter = parameters[originalParameterIndex];
if (argumentIndex > interpolatedStringArgNum)
{
// Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'.
diagnostics.Add(
ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString,
arguments[argumentIndex].Syntax.Location,
parameter.Name,
interpolatedStringParameter.Name);
hasErrors = true;
}
refKind = parameter.RefKind;
placeholderType = parameter.Type;
}
break;
}
SyntaxNode placeholderSyntax;
uint valSafeToEscapeScope;
switch (argumentIndex)
{
case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter:
placeholderSyntax = unconvertedString.Syntax;
valSafeToEscapeScope = receiverEscapeScope;
break;
case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter:
placeholderSyntax = unconvertedString.Syntax;
valSafeToEscapeScope = Binder.ExternalScope;
break;
case >= 0:
placeholderSyntax = arguments[argumentIndex].Syntax;
valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth);
break;
default:
throw ExceptionUtilities.UnexpectedValue(argumentIndex);
}
argumentPlaceholdersBuilder.Add(
new BoundInterpolatedStringArgumentPlaceholder(
placeholderSyntax,
argumentIndex,
valSafeToEscapeScope,
placeholderType,
hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter));
// We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors
// about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will
// be a place where refkinds are allowed to differ
argumentRefKindsBuilder.Add(refKind);
}
var interpolatedString = BindUnconvertedInterpolatedExpressionToHandlerType(
unconvertedString,
(NamedTypeSymbol)interpolatedStringParameter.Type,
diagnostics,
additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(),
additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree());
return new BoundConversion(
interpolatedString.Syntax,
interpolatedString,
interpolatedStringConversion,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: false,
conversionGroupOpt: null,
constantValueOpt: null,
interpolatedStringParameter.Type,
hasErrors || interpolatedString.HasErrors);
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/Core/Portable/PublicAPI.Shipped.txt | abstract Microsoft.CodeAnalysis.CodeActions.CodeAction.Title.get -> string
abstract Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.ComputeOperationsAsync(object options, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
abstract Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.GetOptions(System.Threading.CancellationToken cancellationToken) -> object
abstract Microsoft.CodeAnalysis.CodeActions.PreviewOperation.GetPreviewAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<object>
abstract Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray<string>
abstract Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task
abstract Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider.GetAllDiagnosticsAsync(Microsoft.CodeAnalysis.Project project, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>
abstract Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider.GetDocumentDiagnosticsAsync(Microsoft.CodeAnalysis.Document document, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>
abstract Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider.GetProjectDiagnosticsAsync(Microsoft.CodeAnalysis.Project project, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>
abstract Microsoft.CodeAnalysis.CodeFixes.FixAllProvider.GetFixAsync(Microsoft.CodeAnalysis.CodeFixes.FixAllContext fixAllContext) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.CodeActions.CodeAction>
abstract Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider.ComputeRefactoringsAsync(Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext context) -> System.Threading.Tasks.Task
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetChildren(TNode node) -> System.Collections.Generic.IEnumerable<TNode>
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetDescendants(TNode node) -> System.Collections.Generic.IEnumerable<TNode>
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetDistance(TNode oldNode, TNode newNode) -> double
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetLabel(TNode node) -> int
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetSpan(TNode node) -> Microsoft.CodeAnalysis.Text.TextSpan
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.LabelCount.get -> int
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.TiedToAncestor(int label) -> int
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.TreesEqual(TNode oldNode, TNode newNode) -> bool
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.TryGetParent(TNode node, out TNode parent) -> bool
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.ValuesEqual(TNode oldNode, TNode newNode) -> bool
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddBaseType(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode baseType) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddEventHandler(Microsoft.CodeAnalysis.SyntaxNode event, Microsoft.CodeAnalysis.SyntaxNode handler) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddInterfaceType(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AliasImportDeclaration(string aliasIdentifierName, Microsoft.CodeAnalysis.SyntaxNode name) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Argument(string name, Microsoft.CodeAnalysis.RefKind refKind, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ArrayCreationExpression(Microsoft.CodeAnalysis.SyntaxNode elementType, Microsoft.CodeAnalysis.SyntaxNode size) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ArrayCreationExpression(Microsoft.CodeAnalysis.SyntaxNode elementType, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> elements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ArrayTypeExpression(Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AsPrivateInterfaceImplementation(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType, string interfaceMemberName) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AsPublicInterfaceImplementation(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType, string interfaceMemberName) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AssignmentStatement(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Attribute(Microsoft.CodeAnalysis.SyntaxNode name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributeArguments = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AttributeArgument(string name, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AwaitExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.BaseExpression() -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.BitwiseAndExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.BitwiseNotExpression(Microsoft.CodeAnalysis.SyntaxNode operand) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.BitwiseOrExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CastExpression(Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CatchClause(Microsoft.CodeAnalysis.SyntaxNode type, string identifier, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ClassDeclaration(string name, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), Microsoft.CodeAnalysis.SyntaxNode baseType = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> interfaceTypes = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ClearTrivia<TNode>(TNode node) -> TNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CoalesceExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CompilationUnit(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> declarations) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConditionalAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode whenNotNull) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConditionalExpression(Microsoft.CodeAnalysis.SyntaxNode condition, Microsoft.CodeAnalysis.SyntaxNode whenTrue, Microsoft.CodeAnalysis.SyntaxNode whenFalse) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConstructorDeclaration(string containingTypeName = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> baseConstructorArguments = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConvertExpression(Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CustomEventDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> addAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> removeAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DefaultExpression(Microsoft.CodeAnalysis.ITypeSymbol type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DefaultExpression(Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DefaultSwitchSection(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DelegateDeclaration(string name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.SyntaxNode returnType = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers)) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DivideExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementBindingExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.EnumDeclaration(string name, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.EnumMember(string name, Microsoft.CodeAnalysis.SyntaxNode expression = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.EventDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers)) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ExitSwitchStatement() -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ExpressionStatement(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.FieldDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), Microsoft.CodeAnalysis.SyntaxNode initializer = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GenericName(string identifier, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAccessibility(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.Accessibility
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAccessorDeclaration(Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAccessors(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAttributeArguments(Microsoft.CodeAnalysis.SyntaxNode attributeDeclaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetBaseAndInterfaceTypes(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetDeclarationKind(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.Editing.DeclarationKind
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetExpression(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGetAccessorStatements(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetMembers(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetModifiers(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetName(Microsoft.CodeAnalysis.SyntaxNode declaration) -> string
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetParameters(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetSetAccessorStatements(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetStatements(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetSwitchSections(Microsoft.CodeAnalysis.SyntaxNode switchStatement) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetType(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GreaterThanExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GreaterThanOrEqualExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IdentifierName(string identifier) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IfStatement(Microsoft.CodeAnalysis.SyntaxNode condition, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> trueStatements, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> falseStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IndexerDeclaration(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> getAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> setAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertAccessors(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> accessors) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertAttributeArguments(Microsoft.CodeAnalysis.SyntaxNode attributeDeclaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributes) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertMembers(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> imports) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertParameters(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributes) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertSwitchSections(Microsoft.CodeAnalysis.SyntaxNode switchStatement, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> switchSections) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InterfaceDeclaration(string name, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> interfaceTypes = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InvocationExpression(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IsTypeExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LambdaParameter(string identifier, Microsoft.CodeAnalysis.SyntaxNode type = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LessThanExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LessThanOrEqualExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LiteralExpression(object value) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LocalDeclarationStatement(Microsoft.CodeAnalysis.SyntaxNode type, string identifier, Microsoft.CodeAnalysis.SyntaxNode initializer = null, bool isConst = false) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LockStatement(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LogicalAndExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LogicalNotExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LogicalOrExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MemberBindingExpression(Microsoft.CodeAnalysis.SyntaxNode name) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MethodDeclaration(string name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.SyntaxNode returnType = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ModuloExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MultiplyExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NameExpression(Microsoft.CodeAnalysis.INamespaceOrTypeSymbol namespaceOrTypeSymbol) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NameOfExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceDeclaration(Microsoft.CodeAnalysis.SyntaxNode name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> declarations) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceImportDeclaration(Microsoft.CodeAnalysis.SyntaxNode name) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NegateExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NullableTypeExpression(Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ObjectCreationExpression(Microsoft.CodeAnalysis.SyntaxNode namedType, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ParameterDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type = null, Microsoft.CodeAnalysis.SyntaxNode initializer = null, Microsoft.CodeAnalysis.RefKind refKind = Microsoft.CodeAnalysis.RefKind.None) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.PropertyDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> getAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> setAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.QualifiedName(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReferenceEqualsExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReferenceNotEqualsExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveEventHandler(Microsoft.CodeAnalysis.SyntaxNode event, Microsoft.CodeAnalysis.SyntaxNode handler) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReturnStatement(Microsoft.CodeAnalysis.SyntaxNode expression = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SetAccessorDeclaration(Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.StructDeclaration(string name, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> interfaceTypes = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SubtractExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SwitchSection(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> caseExpressions, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SwitchStatement(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> sections) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ThisExpression() -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ThrowExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ThrowStatement(Microsoft.CodeAnalysis.SyntaxNode expression = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryCastExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryCatchStatement(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> tryStatements, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> catchClauses, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> finallyStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleElementExpression(Microsoft.CodeAnalysis.SyntaxNode type, string name = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypedConstantExpression(Microsoft.CodeAnalysis.TypedConstant value) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypeExpression(Microsoft.CodeAnalysis.ITypeSymbol typeSymbol) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypeExpression(Microsoft.CodeAnalysis.SpecialType specialType) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypeOfExpression(Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.UsingStatement(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.UsingStatement(Microsoft.CodeAnalysis.SyntaxNode type, string name, Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueEqualsExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueNotEqualsExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> lambdaParameters, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> lambdaParameters, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> lambdaParameters, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> lambdaParameters, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WhileStatement(Microsoft.CodeAnalysis.SyntaxNode condition, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithAccessibility(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Accessibility accessibility) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithAccessorDeclarations(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> accessorDeclarations) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithExpression(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithGetAccessorStatements(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithModifiers(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithName(Microsoft.CodeAnalysis.SyntaxNode declaration, string name) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithSetAccessorStatements(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithStatements(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithType(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeArguments(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeConstraint(Microsoft.CodeAnalysis.SyntaxNode declaration, string typeParameterName, Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind kinds, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> types = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeParameters(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<string> typeParameters) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Host.HostLanguageServices.GetService<TLanguageService>() -> TLanguageService
abstract Microsoft.CodeAnalysis.Host.HostLanguageServices.Language.get -> string
abstract Microsoft.CodeAnalysis.Host.HostLanguageServices.WorkspaceServices.get -> Microsoft.CodeAnalysis.Host.HostWorkspaceServices
abstract Microsoft.CodeAnalysis.Host.HostServices.CreateWorkspaceServices(Microsoft.CodeAnalysis.Workspace workspace) -> Microsoft.CodeAnalysis.Host.HostWorkspaceServices
abstract Microsoft.CodeAnalysis.Host.HostWorkspaceServices.FindLanguageServices<TLanguageService>(Microsoft.CodeAnalysis.Host.HostWorkspaceServices.MetadataFilter filter) -> System.Collections.Generic.IEnumerable<TLanguageService>
abstract Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetService<TWorkspaceService>() -> TWorkspaceService
abstract Microsoft.CodeAnalysis.Host.HostWorkspaceServices.HostServices.get -> Microsoft.CodeAnalysis.Host.HostServices
abstract Microsoft.CodeAnalysis.Host.HostWorkspaceServices.Workspace.get -> Microsoft.CodeAnalysis.Workspace
abstract Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.OptionKey optionAndLanguage, object value) -> Microsoft.CodeAnalysis.Options.OptionSet
abstract Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction.GetDescription(System.Globalization.CultureInfo culture = null) -> string
abstract Microsoft.CodeAnalysis.TextLoader.LoadTextAndVersionAsync(Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.DocumentId documentId, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.TextAndVersion>
abstract Microsoft.CodeAnalysis.XmlDocumentationProvider.GetSourceStream(System.Threading.CancellationToken cancellationToken) -> System.IO.Stream
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ClassName = "class name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Comment = "comment" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ConstantName = "constant name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ControlKeyword = "keyword - control" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.DelegateName = "delegate name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.EnumMemberName = "enum member name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.EnumName = "enum name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.EventName = "event name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ExcludedCode = "excluded code" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ExtensionMethodName = "extension method name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.FieldName = "field name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Identifier = "identifier" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.InterfaceName = "interface name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Keyword = "keyword" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.LabelName = "label name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.LocalName = "local name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.MethodName = "method name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ModuleName = "module name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.NamespaceName = "namespace name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.NumericLiteral = "number" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Operator = "operator" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.OperatorOverloaded = "operator - overloaded" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ParameterName = "parameter name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.PreprocessorKeyword = "preprocessor keyword" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.PreprocessorText = "preprocessor text" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.PropertyName = "property name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Punctuation = "punctuation" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexAlternation = "regex - alternation" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexAnchor = "regex - anchor" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexCharacterClass = "regex - character class" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexComment = "regex - comment" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexGrouping = "regex - grouping" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexOtherEscape = "regex - other escape" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexQuantifier = "regex - quantifier" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexSelfEscapedCharacter = "regex - self escaped character" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexText = "regex - text" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.StaticSymbol = "static symbol" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.StringEscapeCharacter = "string - escape character" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.StringLiteral = "string" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.StructName = "struct name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Text = "text" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.TypeParameterName = "type parameter name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.VerbatimStringLiteral = "string - verbatim" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.WhiteSpace = "whitespace" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentAttributeName = "xml doc comment - attribute name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentAttributeQuotes = "xml doc comment - attribute quotes" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentAttributeValue = "xml doc comment - attribute value" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentCDataSection = "xml doc comment - cdata section" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentComment = "xml doc comment - comment" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentDelimiter = "xml doc comment - delimiter" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentEntityReference = "xml doc comment - entity reference" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentName = "xml doc comment - name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentProcessingInstruction = "xml doc comment - processing instruction" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentText = "xml doc comment - text" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralAttributeName = "xml literal - attribute name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralAttributeQuotes = "xml literal - attribute quotes" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralAttributeValue = "xml literal - attribute value" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralCDataSection = "xml literal - cdata section" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralComment = "xml literal - comment" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralDelimiter = "xml literal - delimiter" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralEmbeddedExpression = "xml literal - embedded expression" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralEntityReference = "xml literal - entity reference" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralName = "xml literal - name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralProcessingInstruction = "xml literal - processing instruction" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralText = "xml literal - text" -> string
const Microsoft.CodeAnalysis.CodeActions.ConflictAnnotation.Kind = "CodeAction_Conflict" -> string
const Microsoft.CodeAnalysis.CodeActions.RenameAnnotation.Kind = "CodeAction_Rename" -> string
const Microsoft.CodeAnalysis.CodeActions.WarningAnnotation.Kind = "CodeAction_Warning" -> string
const Microsoft.CodeAnalysis.Host.Mef.ServiceLayer.Default = "Default" -> string
const Microsoft.CodeAnalysis.Host.Mef.ServiceLayer.Desktop = "Desktop" -> string
const Microsoft.CodeAnalysis.Host.Mef.ServiceLayer.Editor = "Editor" -> string
const Microsoft.CodeAnalysis.Host.Mef.ServiceLayer.Host = "Host" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Assembly = "Assembly" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Class = "Class" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Constant = "Constant" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Delegate = "Delegate" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Enum = "Enum" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.EnumMember = "EnumMember" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Error = "Error" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Event = "Event" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.ExtensionMethod = "ExtensionMethod" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Field = "Field" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.File = "File" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Folder = "Folder" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Interface = "Interface" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Internal = "Internal" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Intrinsic = "Intrinsic" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Keyword = "Keyword" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Label = "Label" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Local = "Local" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Method = "Method" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Module = "Module" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Namespace = "Namespace" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Operator = "Operator" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Parameter = "Parameter" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Private = "Private" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Project = "Project" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Property = "Property" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Protected = "Protected" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Public = "Public" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.RangeVariable = "RangeVariable" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Reference = "Reference" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Snippet = "Snippet" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Structure = "Structure" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.TypeParameter = "TypeParameter" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Warning = "Warning" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.Debugger = "Debugger" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.Host = "Host" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.Interactive = "Interactive" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.MetadataAsSource = "MetadataAsSource" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.MiscellaneousFiles = "MiscellaneousFiles" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.MSBuild = "MSBuildWorkspace" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.Preview = "Preview" -> string
Microsoft.CodeAnalysis.AdditionalDocument
Microsoft.CodeAnalysis.AdhocWorkspace
Microsoft.CodeAnalysis.AdhocWorkspace.AddDocument(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.AdhocWorkspace.AddDocument(Microsoft.CodeAnalysis.ProjectId projectId, string name, Microsoft.CodeAnalysis.Text.SourceText text) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.AdhocWorkspace.AddProject(Microsoft.CodeAnalysis.ProjectInfo projectInfo) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.AdhocWorkspace.AddProject(string name, string language) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.AdhocWorkspace.AddProjects(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectInfo> projectInfos) -> void
Microsoft.CodeAnalysis.AdhocWorkspace.AddSolution(Microsoft.CodeAnalysis.SolutionInfo solutionInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.AdhocWorkspace.AdhocWorkspace() -> void
Microsoft.CodeAnalysis.AdhocWorkspace.AdhocWorkspace(Microsoft.CodeAnalysis.Host.HostServices host, string workspaceKind = "Custom") -> void
Microsoft.CodeAnalysis.AdhocWorkspace.ClearSolution() -> void
Microsoft.CodeAnalysis.AnalyzerConfigDocument
Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddAdditionalDocument = 11 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddAnalyzerConfigDocument = 17 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddAnalyzerReference = 9 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddDocument = 6 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddMetadataReference = 4 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddProject = 0 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddProjectReference = 2 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddSolutionAnalyzerReference = 20 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeAdditionalDocument = 13 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeAnalyzerConfigDocument = 19 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeCompilationOptions = 14 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeDocument = 8 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeDocumentInfo = 16 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeParseOptions = 15 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveAdditionalDocument = 12 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveAnalyzerConfigDocument = 18 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveAnalyzerReference = 10 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveDocument = 7 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveMetadataReference = 5 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveProject = 1 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveProjectReference = 3 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveSolutionAnalyzerReference = 21 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.Classification.ClassificationTypeNames
Microsoft.CodeAnalysis.Classification.ClassifiedSpan
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.ClassificationType.get -> string
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.ClassifiedSpan() -> void
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.ClassifiedSpan(Microsoft.CodeAnalysis.Text.TextSpan textSpan, string classificationType) -> void
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.ClassifiedSpan(string classificationType, Microsoft.CodeAnalysis.Text.TextSpan textSpan) -> void
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.Equals(Microsoft.CodeAnalysis.Classification.ClassifiedSpan other) -> bool
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.TextSpan.get -> Microsoft.CodeAnalysis.Text.TextSpan
Microsoft.CodeAnalysis.Classification.Classifier
Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation
Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation.ApplyChangesOperation(Microsoft.CodeAnalysis.Solution changedSolution) -> void
Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation.ChangedSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.CodeActions.CodeAction
Microsoft.CodeAnalysis.CodeActions.CodeAction.CodeAction() -> void
Microsoft.CodeAnalysis.CodeActions.CodeAction.GetOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessAsync(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation> operations, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessChangesAsync(Microsoft.CodeAnalysis.Solution changedSolution, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
Microsoft.CodeAnalysis.CodeActions.CodeActionOperation
Microsoft.CodeAnalysis.CodeActions.CodeActionOperation.CodeActionOperation() -> void
Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions
Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.CodeActionWithOptions() -> void
Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.GetOperationsAsync(object options, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
Microsoft.CodeAnalysis.CodeActions.ConflictAnnotation
Microsoft.CodeAnalysis.CodeActions.OpenDocumentOperation
Microsoft.CodeAnalysis.CodeActions.OpenDocumentOperation.DocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.CodeActions.OpenDocumentOperation.OpenDocumentOperation(Microsoft.CodeAnalysis.DocumentId documentId, bool activateIfAlreadyOpen = false) -> void
Microsoft.CodeAnalysis.CodeActions.PreviewOperation
Microsoft.CodeAnalysis.CodeActions.PreviewOperation.PreviewOperation() -> void
Microsoft.CodeAnalysis.CodeActions.RenameAnnotation
Microsoft.CodeAnalysis.CodeActions.WarningAnnotation
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.CodeFixContext() -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.CodeFixContext(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Diagnostic diagnostic, System.Action<Microsoft.CodeAnalysis.CodeActions.CodeAction, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>> registerCodeFix, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.CodeFixContext(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic> diagnostics, System.Action<Microsoft.CodeAnalysis.CodeActions.CodeAction, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>> registerCodeFix, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.Diagnostics.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.RegisterCodeFix(Microsoft.CodeAnalysis.CodeActions.CodeAction action, Microsoft.CodeAnalysis.Diagnostic diagnostic) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.RegisterCodeFix(Microsoft.CodeAnalysis.CodeActions.CodeAction action, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic> diagnostics) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.RegisterCodeFix(Microsoft.CodeAnalysis.CodeActions.CodeAction action, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic> diagnostics) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.Span.get -> Microsoft.CodeAnalysis.Text.TextSpan
Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider
Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider.CodeFixProvider() -> void
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute.ExportCodeFixProviderAttribute(string firstLanguage, params string[] additionalLanguages) -> void
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute.Languages.get -> string[]
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute.Name.get -> string
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute.Name.set -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllContext
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.CodeActionEquivalenceKey.get -> string
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.CodeFixProvider.get -> Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticIds.get -> System.Collections.Immutable.ImmutableHashSet<string>
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider.DiagnosticProvider() -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.FixAllContext(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider codeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllScope scope, string codeActionEquivalenceKey, System.Collections.Generic.IEnumerable<string> diagnosticIds, Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider fixAllDiagnosticProvider, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.FixAllContext(Microsoft.CodeAnalysis.Project project, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider codeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllScope scope, string codeActionEquivalenceKey, System.Collections.Generic.IEnumerable<string> diagnosticIds, Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider fixAllDiagnosticProvider, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.GetAllDiagnosticsAsync(Microsoft.CodeAnalysis.Project project) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>>
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.GetDocumentDiagnosticsAsync(Microsoft.CodeAnalysis.Document document) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>>
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.GetProjectDiagnosticsAsync(Microsoft.CodeAnalysis.Project project) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>>
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.Project.get -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.Scope.get -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.Solution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.WithCancellationToken(System.Threading.CancellationToken cancellationToken) -> Microsoft.CodeAnalysis.CodeFixes.FixAllContext
Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
Microsoft.CodeAnalysis.CodeFixes.FixAllProvider.FixAllProvider() -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllScope.Custom = 3 -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllScope.Document = 0 -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllScope.Project = 1 -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllScope.Solution = 2 -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.CodeRefactoringContext() -> void
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.CodeRefactoringContext(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, System.Action<Microsoft.CodeAnalysis.CodeActions.CodeAction> registerRefactoring, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.RegisterRefactoring(Microsoft.CodeAnalysis.CodeActions.CodeAction action) -> void
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.Span.get -> Microsoft.CodeAnalysis.Text.TextSpan
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider.CodeRefactoringProvider() -> void
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute.ExportCodeRefactoringProviderAttribute(string firstLanguage, params string[] additionalLanguages) -> void
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute.Languages.get -> string[]
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute.Name.get -> string
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute.Name.set -> void
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.CodeStyleOption(T value, Microsoft.CodeAnalysis.CodeStyle.NotificationOption notification) -> void
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Equals(Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T> other) -> bool
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Notification.get -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Notification.set -> void
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.ToXElement() -> System.Xml.Linq.XElement
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Value.get -> T
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Value.set -> void
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.CodeStyleOptions() -> void
Microsoft.CodeAnalysis.CodeStyle.NotificationOption
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Name.get -> string
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Name.set -> void
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Severity.get -> Microsoft.CodeAnalysis.ReportDiagnostic
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Severity.set -> void
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Value.get -> Microsoft.CodeAnalysis.DiagnosticSeverity
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Value.set -> void
Microsoft.CodeAnalysis.CompilationOutputInfo
Microsoft.CodeAnalysis.CompilationOutputInfo.AssemblyPath.get -> string
Microsoft.CodeAnalysis.CompilationOutputInfo.CompilationOutputInfo() -> void
Microsoft.CodeAnalysis.CompilationOutputInfo.Equals(Microsoft.CodeAnalysis.CompilationOutputInfo other) -> bool
Microsoft.CodeAnalysis.CompilationOutputInfo.WithAssemblyPath(string path) -> Microsoft.CodeAnalysis.CompilationOutputInfo
Microsoft.CodeAnalysis.Differencing.Edit<TNode>
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.Edit() -> void
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.Equals(Microsoft.CodeAnalysis.Differencing.Edit<TNode> other) -> bool
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.Kind.get -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.NewNode.get -> TNode
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.OldNode.get -> TNode
Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Delete = 3 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Insert = 2 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Move = 4 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.None = 0 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Reorder = 5 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Update = 1 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditScript<TNode>
Microsoft.CodeAnalysis.Differencing.EditScript<TNode>.Edits.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Differencing.Edit<TNode>>
Microsoft.CodeAnalysis.Differencing.EditScript<TNode>.Match.get -> Microsoft.CodeAnalysis.Differencing.Match<TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.Comparer.get -> Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.GetSequenceEdits(System.Collections.Generic.IEnumerable<TNode> oldNodes, System.Collections.Generic.IEnumerable<TNode> newNodes) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Differencing.Edit<TNode>>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.GetTreeEdits() -> Microsoft.CodeAnalysis.Differencing.EditScript<TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.Matches.get -> System.Collections.Generic.IReadOnlyDictionary<TNode, TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.NewRoot.get -> TNode
Microsoft.CodeAnalysis.Differencing.Match<TNode>.OldRoot.get -> TNode
Microsoft.CodeAnalysis.Differencing.Match<TNode>.ReverseMatches.get -> System.Collections.Generic.IReadOnlyDictionary<TNode, TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.TryGetNewNode(TNode oldNode, out TNode newNode) -> bool
Microsoft.CodeAnalysis.Differencing.Match<TNode>.TryGetOldNode(TNode newNode, out TNode oldNode) -> bool
Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>
Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.ComputeEditScript(TNode oldRoot, TNode newRoot) -> Microsoft.CodeAnalysis.Differencing.EditScript<TNode>
Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.ComputeMatch(TNode oldRoot, TNode newRoot, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TNode, TNode>> knownMatches = null) -> Microsoft.CodeAnalysis.Differencing.Match<TNode>
Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.TreeComparer() -> void
Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.GetLinkedDocumentIds() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.Document.GetOptionsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Options.DocumentOptionSet>
Microsoft.CodeAnalysis.Document.GetSemanticModelAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SemanticModel>
Microsoft.CodeAnalysis.Document.GetSyntaxRootAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxNode>
Microsoft.CodeAnalysis.Document.GetSyntaxTreeAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxTree>
Microsoft.CodeAnalysis.Document.GetSyntaxVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Document.GetTextChangesAsync(Microsoft.CodeAnalysis.Document oldDocument, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextChange>>
Microsoft.CodeAnalysis.Document.SourceCodeKind.get -> Microsoft.CodeAnalysis.SourceCodeKind
Microsoft.CodeAnalysis.Document.SupportsSemanticModel.get -> bool
Microsoft.CodeAnalysis.Document.SupportsSyntaxTree.get -> bool
Microsoft.CodeAnalysis.Document.TryGetSemanticModel(out Microsoft.CodeAnalysis.SemanticModel semanticModel) -> bool
Microsoft.CodeAnalysis.Document.TryGetSyntaxRoot(out Microsoft.CodeAnalysis.SyntaxNode root) -> bool
Microsoft.CodeAnalysis.Document.TryGetSyntaxTree(out Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> bool
Microsoft.CodeAnalysis.Document.TryGetSyntaxVersion(out Microsoft.CodeAnalysis.VersionStamp version) -> bool
Microsoft.CodeAnalysis.Document.WithFilePath(string filePath) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithFolders(System.Collections.Generic.IEnumerable<string> folders) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithName(string name) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithSourceCodeKind(Microsoft.CodeAnalysis.SourceCodeKind kind) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithSyntaxRoot(Microsoft.CodeAnalysis.SyntaxNode root) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithText(Microsoft.CodeAnalysis.Text.SourceText text) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.DocumentActiveContextChangedEventArgs(Microsoft.CodeAnalysis.Solution solution, Microsoft.CodeAnalysis.Text.SourceTextContainer sourceTextContainer, Microsoft.CodeAnalysis.DocumentId oldActiveContextDocumentId, Microsoft.CodeAnalysis.DocumentId newActiveContextDocumentId) -> void
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.NewActiveContextDocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.OldActiveContextDocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.Solution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.SourceTextContainer.get -> Microsoft.CodeAnalysis.Text.SourceTextContainer
Microsoft.CodeAnalysis.DocumentDiagnostic
Microsoft.CodeAnalysis.DocumentDiagnostic.DocumentDiagnostic(Microsoft.CodeAnalysis.WorkspaceDiagnosticKind kind, string message, Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.DocumentDiagnostic.DocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentEventArgs
Microsoft.CodeAnalysis.DocumentEventArgs.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.DocumentEventArgs.DocumentEventArgs(Microsoft.CodeAnalysis.Document document) -> void
Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentId.Equals(Microsoft.CodeAnalysis.DocumentId other) -> bool
Microsoft.CodeAnalysis.DocumentId.Id.get -> System.Guid
Microsoft.CodeAnalysis.DocumentId.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.FilePath.get -> string
Microsoft.CodeAnalysis.DocumentInfo.Folders.get -> System.Collections.Generic.IReadOnlyList<string>
Microsoft.CodeAnalysis.DocumentInfo.Id.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentInfo.IsGenerated.get -> bool
Microsoft.CodeAnalysis.DocumentInfo.Name.get -> string
Microsoft.CodeAnalysis.DocumentInfo.SourceCodeKind.get -> Microsoft.CodeAnalysis.SourceCodeKind
Microsoft.CodeAnalysis.DocumentInfo.TextLoader.get -> Microsoft.CodeAnalysis.TextLoader
Microsoft.CodeAnalysis.DocumentInfo.WithFilePath(string filePath) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithFolders(System.Collections.Generic.IEnumerable<string> folders) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithId(Microsoft.CodeAnalysis.DocumentId id) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithName(string name) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithSourceCodeKind(Microsoft.CodeAnalysis.SourceCodeKind kind) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithTextLoader(Microsoft.CodeAnalysis.TextLoader loader) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.AddAccessor = 26 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Attribute = 22 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Class = 2 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.CompilationUnit = 1 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Constructor = 10 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.ConversionOperator = 9 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.CustomEvent = 17 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Delegate = 6 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Destructor = 11 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Enum = 5 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.EnumMember = 15 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Event = 16 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Field = 12 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.GetAccessor = 24 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Indexer = 14 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Interface = 4 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.LambdaExpression = 23 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Method = 7 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Namespace = 18 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.NamespaceImport = 19 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.None = 0 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Operator = 8 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Parameter = 20 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Property = 13 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.RaiseAccessor = 28 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.RemoveAccessor = 27 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.SetAccessor = 25 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Struct = 3 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Variable = 21 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.DeclarationModifiers() -> void
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Equals(Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsAbstract.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsAsync.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsConst.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsExtern.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsNew.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsOverride.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsPartial.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsReadOnly.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsRef.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsSealed.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsStatic.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsUnsafe.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsVirtual.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsVolatile.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsWithEvents.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsWriteOnly.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithAsync(bool isAsync) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsAbstract(bool isAbstract) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsConst(bool isConst) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsExtern(bool isExtern) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsNew(bool isNew) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsOverride(bool isOverride) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsReadOnly(bool isReadOnly) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsRef(bool isRef) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsSealed(bool isSealed) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsStatic(bool isStatic) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsUnsafe(bool isUnsafe) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsVirtual(bool isVirtual) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsVolatile(bool isVolatile) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsWriteOnly(bool isWriteOnly) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithPartial(bool isPartial) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithWithEvents(bool withEvents) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DocumentEditor
Microsoft.CodeAnalysis.Editing.DocumentEditor.GetChangedDocument() -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Editing.DocumentEditor.OriginalDocument.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Editing.DocumentEditor.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel
Microsoft.CodeAnalysis.Editing.ImportAdder
Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Addition = 2 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.BitwiseAnd = 3 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.BitwiseOr = 4 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Decrement = 5 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Division = 6 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Equality = 7 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.ExclusiveOr = 8 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.ExplicitConversion = 1 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.False = 9 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.GreaterThan = 10 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.GreaterThanOrEqual = 11 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.ImplicitConversion = 0 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Increment = 12 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Inequality = 13 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.LeftShift = 14 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.LessThan = 15 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.LessThanOrEqual = 16 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.LogicalNot = 17 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Modulus = 18 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Multiply = 19 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.OnesComplement = 20 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.RightShift = 21 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Subtraction = 22 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.True = 23 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.UnaryNegation = 24 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.UnaryPlus = 25 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.SolutionEditor
Microsoft.CodeAnalysis.Editing.SolutionEditor.GetChangedSolution() -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Editing.SolutionEditor.GetDocumentEditorAsync(Microsoft.CodeAnalysis.DocumentId id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Editing.DocumentEditor>
Microsoft.CodeAnalysis.Editing.SolutionEditor.OriginalSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Editing.SolutionEditor.SolutionEditor(Microsoft.CodeAnalysis.Solution solution) -> void
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind.Constructor = 4 -> Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind.None = 0 -> Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind.ReferenceType = 1 -> Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind.ValueType = 2 -> Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SymbolEditor
Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction
Microsoft.CodeAnalysis.Editing.SymbolEditor.ChangedSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditAllDeclarationsAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditAllDeclarationsAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.ISymbol member, Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.ISymbol member, Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Location location, Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Location location, Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.GetChangedDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Document>
Microsoft.CodeAnalysis.Editing.SymbolEditor.GetCurrentDeclarationsAsync(Microsoft.CodeAnalysis.ISymbol symbol, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>>
Microsoft.CodeAnalysis.Editing.SymbolEditor.GetCurrentSymbolAsync(Microsoft.CodeAnalysis.ISymbol symbol, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.OriginalSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Editing.SymbolEditorExtensions
Microsoft.CodeAnalysis.Editing.SyntaxEditor
Microsoft.CodeAnalysis.Editing.SyntaxEditor.Generator.get -> Microsoft.CodeAnalysis.Editing.SyntaxGenerator
Microsoft.CodeAnalysis.Editing.SyntaxEditor.GetChangedRoot() -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxEditor.InsertAfter(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxNode newNode) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.InsertAfter(Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> newNodes) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.InsertBefore(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxNode newNode) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.InsertBefore(Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> newNodes) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.OriginalRoot.get -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxEditor.RemoveNode(Microsoft.CodeAnalysis.SyntaxNode node) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.RemoveNode(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxRemoveOptions options) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.ReplaceNode(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxNode newNode) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.ReplaceNode(Microsoft.CodeAnalysis.SyntaxNode node, System.Func<Microsoft.CodeAnalysis.SyntaxNode, Microsoft.CodeAnalysis.Editing.SyntaxGenerator, Microsoft.CodeAnalysis.SyntaxNode> computeReplacement) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.SyntaxEditor(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.Workspace workspace) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.TrackNode(Microsoft.CodeAnalysis.SyntaxNode node) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions
Microsoft.CodeAnalysis.Editing.SyntaxGenerator
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddAccessors(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> accessors) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddAttributeArguments(Microsoft.CodeAnalysis.SyntaxNode attributeDeclaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddMembers(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] members) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddMembers(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] imports) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> imports) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddParameters(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddSwitchSections(Microsoft.CodeAnalysis.SyntaxNode switchStatement, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> switchSections) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AliasImportDeclaration(string aliasIdentifierName, Microsoft.CodeAnalysis.INamespaceOrTypeSymbol symbol) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Argument(Microsoft.CodeAnalysis.RefKind refKind, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Argument(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AsPrivateInterfaceImplementation(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AsPublicInterfaceImplementation(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Attribute(Microsoft.CodeAnalysis.AttributeData attribute) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Attribute(string name, params Microsoft.CodeAnalysis.SyntaxNode[] attributeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Attribute(string name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributeArguments = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AttributeArgument(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CastExpression(Microsoft.CodeAnalysis.ITypeSymbol type, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CatchClause(Microsoft.CodeAnalysis.ITypeSymbol type, string identifier, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CompilationUnit(params Microsoft.CodeAnalysis.SyntaxNode[] declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConstructorDeclaration(Microsoft.CodeAnalysis.IMethodSymbol constructorMethod, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> baseConstructorArguments = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConvertExpression(Microsoft.CodeAnalysis.ITypeSymbol type, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CustomEventDeclaration(Microsoft.CodeAnalysis.IEventSymbol symbol, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> addAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> removeAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Declaration(Microsoft.CodeAnalysis.ISymbol symbol) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DottedName(string dottedName) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementBindingExpression(params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.EventDeclaration(Microsoft.CodeAnalysis.IEventSymbol symbol) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.FalseLiteralExpression() -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.FieldDeclaration(Microsoft.CodeAnalysis.IFieldSymbol field) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.FieldDeclaration(Microsoft.CodeAnalysis.IFieldSymbol field, Microsoft.CodeAnalysis.SyntaxNode initializer) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GenericName(string identifier, params Microsoft.CodeAnalysis.ITypeSymbol[] typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GenericName(string identifier, params Microsoft.CodeAnalysis.SyntaxNode[] typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GenericName(string identifier, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ITypeSymbol> typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAccessor(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Editing.DeclarationKind kind) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetDeclaration(Microsoft.CodeAnalysis.SyntaxNode node) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetDeclaration(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Editing.DeclarationKind kind) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IfStatement(Microsoft.CodeAnalysis.SyntaxNode condition, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> trueStatements, Microsoft.CodeAnalysis.SyntaxNode falseStatement) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IndexerDeclaration(Microsoft.CodeAnalysis.IPropertySymbol indexer, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> getAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> setAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IndexOf<T>(System.Collections.Generic.IReadOnlyList<T> list, T element) -> int
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, params Microsoft.CodeAnalysis.SyntaxNode[] attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertMembers(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, params Microsoft.CodeAnalysis.SyntaxNode[] members) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, params Microsoft.CodeAnalysis.SyntaxNode[] imports) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, params Microsoft.CodeAnalysis.SyntaxNode[] attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InvocationExpression(Microsoft.CodeAnalysis.SyntaxNode expression, params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IsTypeExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.ITypeSymbol type) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LambdaParameter(string identifier, Microsoft.CodeAnalysis.ITypeSymbol type) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LocalDeclarationStatement(Microsoft.CodeAnalysis.ITypeSymbol type, string name, Microsoft.CodeAnalysis.SyntaxNode initializer = null, bool isConst = false) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LocalDeclarationStatement(string name, Microsoft.CodeAnalysis.SyntaxNode initializer) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MemberAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, string memberName) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MethodDeclaration(Microsoft.CodeAnalysis.IMethodSymbol method, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceDeclaration(Microsoft.CodeAnalysis.SyntaxNode name, params Microsoft.CodeAnalysis.SyntaxNode[] declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceDeclaration(string name, params Microsoft.CodeAnalysis.SyntaxNode[] declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceDeclaration(string name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceImportDeclaration(string name) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NullLiteralExpression() -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ObjectCreationExpression(Microsoft.CodeAnalysis.ITypeSymbol type, params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ObjectCreationExpression(Microsoft.CodeAnalysis.ITypeSymbol type, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ObjectCreationExpression(Microsoft.CodeAnalysis.SyntaxNode type, params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.OperatorDeclaration(Microsoft.CodeAnalysis.IMethodSymbol method, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ParameterDeclaration(Microsoft.CodeAnalysis.IParameterSymbol symbol, Microsoft.CodeAnalysis.SyntaxNode initializer = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.PropertyDeclaration(Microsoft.CodeAnalysis.IPropertySymbol property, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> getAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> setAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveAllAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveNodes(Microsoft.CodeAnalysis.SyntaxNode root, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SwitchSection(Microsoft.CodeAnalysis.SyntaxNode caseExpression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SwitchStatement(Microsoft.CodeAnalysis.SyntaxNode expression, params Microsoft.CodeAnalysis.SyntaxNode[] sections) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SyntaxGenerator() -> void
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TrueLiteralExpression() -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryCastExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.ITypeSymbol type) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryCatchStatement(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> tryStatements, params Microsoft.CodeAnalysis.SyntaxNode[] catchClauses) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryFinallyStatement(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> tryStatements, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> finallyStatements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleElementExpression(Microsoft.CodeAnalysis.ITypeSymbol type, string name = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleTypeExpression(params Microsoft.CodeAnalysis.SyntaxNode[] elements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleTypeExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ITypeSymbol> elementTypes, System.Collections.Generic.IEnumerable<string> elementNames = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleTypeExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> elements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypeExpression(Microsoft.CodeAnalysis.ITypeSymbol typeSymbol, bool addImport) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.UsingStatement(string name, Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(string parameterName, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(string parameterName, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(string parameterName, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(string parameterName, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithAccessorDeclarations(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] accessorDeclarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeArguments(Microsoft.CodeAnalysis.SyntaxNode expression, params Microsoft.CodeAnalysis.SyntaxNode[] typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeConstraint(Microsoft.CodeAnalysis.SyntaxNode declaration, string typeParameterName, Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind kinds, params Microsoft.CodeAnalysis.SyntaxNode[] types) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeConstraint(Microsoft.CodeAnalysis.SyntaxNode declaration, string typeParameterName, params Microsoft.CodeAnalysis.SyntaxNode[] types) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeParameters(Microsoft.CodeAnalysis.SyntaxNode declaration, params string[] typeParameters) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.ExtensionOrderAttribute
Microsoft.CodeAnalysis.ExtensionOrderAttribute.After.get -> string
Microsoft.CodeAnalysis.ExtensionOrderAttribute.After.set -> void
Microsoft.CodeAnalysis.ExtensionOrderAttribute.Before.get -> string
Microsoft.CodeAnalysis.ExtensionOrderAttribute.Before.set -> void
Microsoft.CodeAnalysis.ExtensionOrderAttribute.ExtensionOrderAttribute() -> void
Microsoft.CodeAnalysis.FileTextLoader
Microsoft.CodeAnalysis.FileTextLoader.DefaultEncoding.get -> System.Text.Encoding
Microsoft.CodeAnalysis.FileTextLoader.FileTextLoader(string path, System.Text.Encoding defaultEncoding) -> void
Microsoft.CodeAnalysis.FileTextLoader.Path.get -> string
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnCompleted() -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnDefinitionFound(Microsoft.CodeAnalysis.ISymbol symbol) -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnFindInDocumentCompleted(Microsoft.CodeAnalysis.Document document) -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnFindInDocumentStarted(Microsoft.CodeAnalysis.Document document) -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnReferenceFound(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation location) -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnStarted() -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.ReportProgress(int current, int maximum) -> void
Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol
Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol.Definition.get -> Microsoft.CodeAnalysis.ISymbol
Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol.Locations.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation>
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Alias.get -> Microsoft.CodeAnalysis.IAliasSymbol
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.CandidateReason.get -> Microsoft.CodeAnalysis.CandidateReason
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.CompareTo(Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation other) -> int
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Equals(Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation other) -> bool
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.IsCandidateLocation.get -> bool
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.IsImplicit.get -> bool
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Location.get -> Microsoft.CodeAnalysis.Location
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.ReferenceLocation() -> void
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.CalledSymbol.get -> Microsoft.CodeAnalysis.ISymbol
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.CallingSymbol.get -> Microsoft.CodeAnalysis.ISymbol
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.IsDirect.get -> bool
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.Locations.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Location>
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.SymbolCallerInfo() -> void
Microsoft.CodeAnalysis.FindSymbols.SymbolFinder
Microsoft.CodeAnalysis.Formatting.Formatter
Microsoft.CodeAnalysis.Formatting.FormattingOptions
Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle
Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Block = 1 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle
Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.None = 0 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle
Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Smart = 2 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle
Microsoft.CodeAnalysis.Host.HostLanguageServices
Microsoft.CodeAnalysis.Host.HostLanguageServices.GetRequiredService<TLanguageService>() -> TLanguageService
Microsoft.CodeAnalysis.Host.HostLanguageServices.HostLanguageServices() -> void
Microsoft.CodeAnalysis.Host.HostServices
Microsoft.CodeAnalysis.Host.HostServices.HostServices() -> void
Microsoft.CodeAnalysis.Host.HostWorkspaceServices
Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetRequiredService<TWorkspaceService>() -> TWorkspaceService
Microsoft.CodeAnalysis.Host.HostWorkspaceServices.HostWorkspaceServices() -> void
Microsoft.CodeAnalysis.Host.HostWorkspaceServices.MetadataFilter
Microsoft.CodeAnalysis.Host.IAnalyzerService
Microsoft.CodeAnalysis.Host.IAnalyzerService.GetLoader() -> Microsoft.CodeAnalysis.IAnalyzerAssemblyLoader
Microsoft.CodeAnalysis.Host.ILanguageService
Microsoft.CodeAnalysis.Host.IPersistentStorage
Microsoft.CodeAnalysis.Host.IPersistentStorage.ReadStreamAsync(Microsoft.CodeAnalysis.Document document, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.IO.Stream>
Microsoft.CodeAnalysis.Host.IPersistentStorage.ReadStreamAsync(Microsoft.CodeAnalysis.Project project, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.IO.Stream>
Microsoft.CodeAnalysis.Host.IPersistentStorage.ReadStreamAsync(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.IO.Stream>
Microsoft.CodeAnalysis.Host.IPersistentStorage.WriteStreamAsync(Microsoft.CodeAnalysis.Document document, string name, System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<bool>
Microsoft.CodeAnalysis.Host.IPersistentStorage.WriteStreamAsync(Microsoft.CodeAnalysis.Project project, string name, System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<bool>
Microsoft.CodeAnalysis.Host.IPersistentStorage.WriteStreamAsync(string name, System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<bool>
Microsoft.CodeAnalysis.Host.IPersistentStorageService
Microsoft.CodeAnalysis.Host.IPersistentStorageService.GetStorage(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.Host.IPersistentStorage
Microsoft.CodeAnalysis.Host.ITemporaryStorageService
Microsoft.CodeAnalysis.Host.ITemporaryStorageService.CreateTemporaryStreamStorage(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage
Microsoft.CodeAnalysis.Host.ITemporaryStorageService.CreateTemporaryTextStorage(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Host.ITemporaryTextStorage
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage.ReadStream(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.IO.Stream
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage.ReadStreamAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.IO.Stream>
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage.WriteStream(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage.WriteStreamAsync(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage.ReadText(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Text.SourceText
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage.ReadTextAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Text.SourceText>
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage.WriteText(Microsoft.CodeAnalysis.Text.SourceText text, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage.WriteTextAsync(Microsoft.CodeAnalysis.Text.SourceText text, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Host.IWorkspaceService
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute.ExportLanguageServiceAttribute(System.Type type, string language, string layer = "Default") -> void
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute.Language.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute.Layer.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute.ServiceType.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute.ExportLanguageServiceFactoryAttribute(System.Type type, string language, string layer = "Default") -> void
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute.Language.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute.Layer.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute.ServiceType.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceAttribute
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceAttribute.ExportWorkspaceServiceAttribute(System.Type serviceType, string layer = "Default") -> void
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceAttribute.Layer.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceAttribute.ServiceType.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceFactoryAttribute
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceFactoryAttribute.ExportWorkspaceServiceFactoryAttribute(System.Type serviceType, string layer = "Default") -> void
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceFactoryAttribute.Layer.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceFactoryAttribute.ServiceType.get -> string
Microsoft.CodeAnalysis.Host.Mef.ILanguageServiceFactory
Microsoft.CodeAnalysis.Host.Mef.ILanguageServiceFactory.CreateLanguageService(Microsoft.CodeAnalysis.Host.HostLanguageServices languageServices) -> Microsoft.CodeAnalysis.Host.ILanguageService
Microsoft.CodeAnalysis.Host.Mef.IWorkspaceServiceFactory
Microsoft.CodeAnalysis.Host.Mef.IWorkspaceServiceFactory.CreateService(Microsoft.CodeAnalysis.Host.HostWorkspaceServices workspaceServices) -> Microsoft.CodeAnalysis.Host.IWorkspaceService
Microsoft.CodeAnalysis.Host.Mef.MefHostServices
Microsoft.CodeAnalysis.Host.Mef.MefHostServices.MefHostServices(System.Composition.CompositionContext compositionContext) -> void
Microsoft.CodeAnalysis.Host.Mef.ServiceLayer
Microsoft.CodeAnalysis.Options.DocumentOptionSet
Microsoft.CodeAnalysis.Options.DocumentOptionSet.GetOption<T>(Microsoft.CodeAnalysis.Options.PerLanguageOption<T> option) -> T
Microsoft.CodeAnalysis.Options.DocumentOptionSet.WithChangedOption<T>(Microsoft.CodeAnalysis.Options.PerLanguageOption<T> option, T value) -> Microsoft.CodeAnalysis.Options.DocumentOptionSet
Microsoft.CodeAnalysis.Options.IOption
Microsoft.CodeAnalysis.Options.IOption.DefaultValue.get -> object
Microsoft.CodeAnalysis.Options.IOption.Feature.get -> string
Microsoft.CodeAnalysis.Options.IOption.IsPerLanguage.get -> bool
Microsoft.CodeAnalysis.Options.IOption.Name.get -> string
Microsoft.CodeAnalysis.Options.IOption.StorageLocations.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Options.OptionStorageLocation>
Microsoft.CodeAnalysis.Options.IOption.Type.get -> System.Type
Microsoft.CodeAnalysis.Options.Option<T>
Microsoft.CodeAnalysis.Options.Option<T>.DefaultValue.get -> T
Microsoft.CodeAnalysis.Options.Option<T>.Feature.get -> string
Microsoft.CodeAnalysis.Options.Option<T>.Name.get -> string
Microsoft.CodeAnalysis.Options.Option<T>.Option(string feature, string name) -> void
Microsoft.CodeAnalysis.Options.Option<T>.Option(string feature, string name, T defaultValue) -> void
Microsoft.CodeAnalysis.Options.Option<T>.Option(string feature, string name, T defaultValue, params Microsoft.CodeAnalysis.Options.OptionStorageLocation[] storageLocations) -> void
Microsoft.CodeAnalysis.Options.Option<T>.StorageLocations.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Options.OptionStorageLocation>
Microsoft.CodeAnalysis.Options.Option<T>.Type.get -> System.Type
Microsoft.CodeAnalysis.Options.OptionKey
Microsoft.CodeAnalysis.Options.OptionKey.Equals(Microsoft.CodeAnalysis.Options.OptionKey other) -> bool
Microsoft.CodeAnalysis.Options.OptionKey.Language.get -> string
Microsoft.CodeAnalysis.Options.OptionKey.Option.get -> Microsoft.CodeAnalysis.Options.IOption
Microsoft.CodeAnalysis.Options.OptionKey.OptionKey() -> void
Microsoft.CodeAnalysis.Options.OptionKey.OptionKey(Microsoft.CodeAnalysis.Options.IOption option, string language = null) -> void
Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Options.OptionSet.GetOption(Microsoft.CodeAnalysis.Options.OptionKey optionKey) -> object
Microsoft.CodeAnalysis.Options.OptionSet.GetOption<T>(Microsoft.CodeAnalysis.Options.Option<T> option) -> T
Microsoft.CodeAnalysis.Options.OptionSet.GetOption<T>(Microsoft.CodeAnalysis.Options.OptionKey optionKey) -> T
Microsoft.CodeAnalysis.Options.OptionSet.GetOption<T>(Microsoft.CodeAnalysis.Options.PerLanguageOption<T> option, string language) -> T
Microsoft.CodeAnalysis.Options.OptionSet.OptionSet() -> void
Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption<T>(Microsoft.CodeAnalysis.Options.Option<T> option, T value) -> Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption<T>(Microsoft.CodeAnalysis.Options.PerLanguageOption<T> option, string language, T value) -> Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Options.OptionStorageLocation
Microsoft.CodeAnalysis.Options.OptionStorageLocation.OptionStorageLocation() -> void
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.DefaultValue.get -> T
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.Feature.get -> string
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.Name.get -> string
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.PerLanguageOption(string feature, string name, T defaultValue) -> void
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.PerLanguageOption(string feature, string name, T defaultValue, params Microsoft.CodeAnalysis.Options.OptionStorageLocation[] storageLocations) -> void
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.StorageLocations.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Options.OptionStorageLocation>
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.Type.get -> System.Type
Microsoft.CodeAnalysis.PreservationMode
Microsoft.CodeAnalysis.PreservationMode.PreserveIdentity = 1 -> Microsoft.CodeAnalysis.PreservationMode
Microsoft.CodeAnalysis.PreservationMode.PreserveValue = 0 -> Microsoft.CodeAnalysis.PreservationMode
Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddAdditionalDocument(string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Project.AddAdditionalDocument(string name, string text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Project.AddAnalyzerConfigDocument(string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Project.AddAnalyzerReference(Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddDocument(string name, Microsoft.CodeAnalysis.SyntaxNode syntaxRoot, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.AddDocument(string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.AddDocument(string name, string text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.AdditionalDocumentIds.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.Project.AdditionalDocuments.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.TextDocument>
Microsoft.CodeAnalysis.Project.AddMetadataReference(Microsoft.CodeAnalysis.MetadataReference metadataReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddMetadataReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddProjectReference(Microsoft.CodeAnalysis.ProjectReference projectReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddProjectReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AllProjectReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.Project.AnalyzerConfigDocuments.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.AnalyzerConfigDocument>
Microsoft.CodeAnalysis.Project.AnalyzerOptions.get -> Microsoft.CodeAnalysis.Diagnostics.AnalyzerOptions
Microsoft.CodeAnalysis.Project.AnalyzerReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.Project.AssemblyName.get -> string
Microsoft.CodeAnalysis.Project.CompilationOptions.get -> Microsoft.CodeAnalysis.CompilationOptions
Microsoft.CodeAnalysis.Project.CompilationOutputInfo.get -> Microsoft.CodeAnalysis.CompilationOutputInfo
Microsoft.CodeAnalysis.Project.ContainsAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Project.ContainsAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Project.ContainsDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Project.DefaultNamespace.get -> string
Microsoft.CodeAnalysis.Project.DocumentIds.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.Project.Documents.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Document>
Microsoft.CodeAnalysis.Project.FilePath.get -> string
Microsoft.CodeAnalysis.Project.GetAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Project.GetAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.AnalyzerConfigDocument
Microsoft.CodeAnalysis.Project.GetChanges(Microsoft.CodeAnalysis.Project oldProject) -> Microsoft.CodeAnalysis.ProjectChanges
Microsoft.CodeAnalysis.Project.GetCompilationAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Compilation>
Microsoft.CodeAnalysis.Project.GetDependentSemanticVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Project.GetDependentVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Project.GetDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.GetDocument(Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.GetDocumentId(Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.Project.GetLatestDocumentVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Project.GetSemanticVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Project.HasDocuments.get -> bool
Microsoft.CodeAnalysis.Project.Id.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.Project.IsSubmission.get -> bool
Microsoft.CodeAnalysis.Project.Language.get -> string
Microsoft.CodeAnalysis.Project.LanguageServices.get -> Microsoft.CodeAnalysis.Host.HostLanguageServices
Microsoft.CodeAnalysis.Project.MetadataReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.MetadataReference>
Microsoft.CodeAnalysis.Project.Name.get -> string
Microsoft.CodeAnalysis.Project.OutputFilePath.get -> string
Microsoft.CodeAnalysis.Project.OutputRefFilePath.get -> string
Microsoft.CodeAnalysis.Project.ParseOptions.get -> Microsoft.CodeAnalysis.ParseOptions
Microsoft.CodeAnalysis.Project.ProjectReferences.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.Project.RemoveAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveAdditionalDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveAnalyzerConfigDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveAnalyzerReference(Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveMetadataReference(Microsoft.CodeAnalysis.MetadataReference metadataReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveProjectReference(Microsoft.CodeAnalysis.ProjectReference projectReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.Solution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Project.SupportsCompilation.get -> bool
Microsoft.CodeAnalysis.Project.TryGetCompilation(out Microsoft.CodeAnalysis.Compilation compilation) -> bool
Microsoft.CodeAnalysis.Project.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.Project.WithAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferencs) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithAssemblyName(string assemblyName) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithCompilationOptions(Microsoft.CodeAnalysis.CompilationOptions options) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithDefaultNamespace(string defaultNamespace) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithMetadataReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithParseOptions(Microsoft.CodeAnalysis.ParseOptions options) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithProjectReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.ProjectChanges
Microsoft.CodeAnalysis.ProjectChanges.GetAddedAdditionalDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedAnalyzerConfigDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedAnalyzerReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedMetadataReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedProjectReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.ProjectChanges.GetChangedAdditionalDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetChangedAnalyzerConfigDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetChangedDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetChangedDocuments(bool onlyGetDocumentsWithTextChanges) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedAdditionalDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedAnalyzerConfigDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedAnalyzerReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedMetadataReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedProjectReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.ProjectChanges.NewProject.get -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.ProjectChanges.OldProject.get -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.ProjectChanges.ProjectChanges() -> void
Microsoft.CodeAnalysis.ProjectChanges.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectDependencyGraph
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetDependencySets(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectId>>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetProjectsThatDirectlyDependOnThisProject(Microsoft.CodeAnalysis.ProjectId projectId) -> System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetProjectsThatThisProjectDirectlyDependsOn(Microsoft.CodeAnalysis.ProjectId projectId) -> System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(Microsoft.CodeAnalysis.ProjectId projectId) -> System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(Microsoft.CodeAnalysis.ProjectId projectId) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetTopologicallySortedProjects(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDiagnostic
Microsoft.CodeAnalysis.ProjectDiagnostic.ProjectDiagnostic(Microsoft.CodeAnalysis.WorkspaceDiagnosticKind kind, string message, Microsoft.CodeAnalysis.ProjectId projectId) -> void
Microsoft.CodeAnalysis.ProjectDiagnostic.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectId.Equals(Microsoft.CodeAnalysis.ProjectId other) -> bool
Microsoft.CodeAnalysis.ProjectId.Id.get -> System.Guid
Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.AdditionalDocuments.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentInfo>
Microsoft.CodeAnalysis.ProjectInfo.AnalyzerConfigDocuments.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentInfo>
Microsoft.CodeAnalysis.ProjectInfo.AnalyzerReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.ProjectInfo.AssemblyName.get -> string
Microsoft.CodeAnalysis.ProjectInfo.CompilationOptions.get -> Microsoft.CodeAnalysis.CompilationOptions
Microsoft.CodeAnalysis.ProjectInfo.CompilationOutputInfo.get -> Microsoft.CodeAnalysis.CompilationOutputInfo
Microsoft.CodeAnalysis.ProjectInfo.Documents.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentInfo>
Microsoft.CodeAnalysis.ProjectInfo.FilePath.get -> string
Microsoft.CodeAnalysis.ProjectInfo.HostObjectType.get -> System.Type
Microsoft.CodeAnalysis.ProjectInfo.Id.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectInfo.IsSubmission.get -> bool
Microsoft.CodeAnalysis.ProjectInfo.Language.get -> string
Microsoft.CodeAnalysis.ProjectInfo.MetadataReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.MetadataReference>
Microsoft.CodeAnalysis.ProjectInfo.Name.get -> string
Microsoft.CodeAnalysis.ProjectInfo.OutputFilePath.get -> string
Microsoft.CodeAnalysis.ProjectInfo.OutputRefFilePath.get -> string
Microsoft.CodeAnalysis.ProjectInfo.ParseOptions.get -> Microsoft.CodeAnalysis.ParseOptions
Microsoft.CodeAnalysis.ProjectInfo.ProjectReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.ProjectInfo.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.ProjectInfo.WithAdditionalDocuments(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> additionalDocuments) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithAnalyzerConfigDocuments(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> analyzerConfigDocuments) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithAssemblyName(string assemblyName) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithCompilationOptions(Microsoft.CodeAnalysis.CompilationOptions compilationOptions) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithCompilationOutputInfo(in Microsoft.CodeAnalysis.CompilationOutputInfo info) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithDefaultNamespace(string defaultNamespace) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithDocuments(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> documents) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithFilePath(string filePath) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithMetadataReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithName(string name) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithOutputFilePath(string outputFilePath) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithOutputRefFilePath(string outputRefFilePath) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithParseOptions(Microsoft.CodeAnalysis.ParseOptions parseOptions) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithProjectReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithVersion(Microsoft.CodeAnalysis.VersionStamp version) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectReference
Microsoft.CodeAnalysis.ProjectReference.Aliases.get -> System.Collections.Immutable.ImmutableArray<string>
Microsoft.CodeAnalysis.ProjectReference.EmbedInteropTypes.get -> bool
Microsoft.CodeAnalysis.ProjectReference.Equals(Microsoft.CodeAnalysis.ProjectReference reference) -> bool
Microsoft.CodeAnalysis.ProjectReference.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectReference.ProjectReference(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Immutable.ImmutableArray<string> aliases = default(System.Collections.Immutable.ImmutableArray<string>), bool embedInteropTypes = false) -> void
Microsoft.CodeAnalysis.Recommendations.RecommendationOptions
Microsoft.CodeAnalysis.Recommendations.Recommender
Microsoft.CodeAnalysis.Rename.RenameEntityKind
Microsoft.CodeAnalysis.Rename.RenameEntityKind.BaseSymbol = 0 -> Microsoft.CodeAnalysis.Rename.RenameEntityKind
Microsoft.CodeAnalysis.Rename.RenameEntityKind.OverloadedSymbols = 1 -> Microsoft.CodeAnalysis.Rename.RenameEntityKind
Microsoft.CodeAnalysis.Rename.RenameOptions
Microsoft.CodeAnalysis.Rename.Renamer
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction.GetErrors(System.Globalization.CultureInfo culture = null) -> System.Collections.Immutable.ImmutableArray<string>
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet.ApplicableActions.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction>
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet.UpdateSolutionAsync(Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction> actions, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet.UpdateSolutionAsync(Microsoft.CodeAnalysis.Solution solution, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
Microsoft.CodeAnalysis.Simplification.SimplificationOptions
Microsoft.CodeAnalysis.Simplification.Simplifier
Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, string text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAdditionalDocument(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAdditionalDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentInfo> documentInfos) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerConfigDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentInfo> documentInfos) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerReference(Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.SyntaxNode syntaxRoot, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false, Microsoft.CodeAnalysis.PreservationMode preservationMode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.TextLoader loader, System.Collections.Generic.IEnumerable<string> folders = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, string text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentInfo> documentInfos) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddMetadataReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddMetadataReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddProject(Microsoft.CodeAnalysis.ProjectId projectId, string name, string assemblyName, string language) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddProject(Microsoft.CodeAnalysis.ProjectInfo projectInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddProject(string name, string assemblyName, string language) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Solution.AddProjectReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddProjectReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AnalyzerReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.Solution.ContainsAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Solution.ContainsAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Solution.ContainsDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Solution.ContainsProject(Microsoft.CodeAnalysis.ProjectId projectId) -> bool
Microsoft.CodeAnalysis.Solution.FilePath.get -> string
Microsoft.CodeAnalysis.Solution.GetAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Solution.GetAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.AnalyzerConfigDocument
Microsoft.CodeAnalysis.Solution.GetChanges(Microsoft.CodeAnalysis.Solution oldSolution) -> Microsoft.CodeAnalysis.SolutionChanges
Microsoft.CodeAnalysis.Solution.GetDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Solution.GetDocument(Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Solution.GetDocumentId(Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.Solution.GetDocumentId(Microsoft.CodeAnalysis.SyntaxTree syntaxTree, Microsoft.CodeAnalysis.ProjectId projectId) -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.Solution.GetDocumentIdsWithFilePath(string filePath) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.Solution.GetIsolatedSolution() -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.GetLatestProjectVersion() -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.Solution.GetProject(Microsoft.CodeAnalysis.IAssemblySymbol assemblySymbol, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Solution.GetProject(Microsoft.CodeAnalysis.ProjectId projectId) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Solution.GetProjectDependencyGraph() -> Microsoft.CodeAnalysis.ProjectDependencyGraph
Microsoft.CodeAnalysis.Solution.Id.get -> Microsoft.CodeAnalysis.SolutionId
Microsoft.CodeAnalysis.Solution.Options.get -> Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Solution.ProjectIds.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.Solution.Projects.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Project>
Microsoft.CodeAnalysis.Solution.RemoveAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAdditionalDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAnalyzerConfigDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAnalyzerReference(Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAnalyzerReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveMetadataReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveProject(Microsoft.CodeAnalysis.ProjectId projectId) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveProjectReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.Solution.WithAdditionalDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAdditionalDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextAndVersion textAndVersion, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAdditionalDocumentTextLoader(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader, Microsoft.CodeAnalysis.PreservationMode mode) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAnalyzerConfigDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAnalyzerConfigDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextAndVersion textAndVersion, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAnalyzerConfigDocumentTextLoader(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader, Microsoft.CodeAnalysis.PreservationMode mode) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentFilePath(Microsoft.CodeAnalysis.DocumentId documentId, string filePath) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentFolders(Microsoft.CodeAnalysis.DocumentId documentId, System.Collections.Generic.IEnumerable<string> folders) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentName(Microsoft.CodeAnalysis.DocumentId documentId, string name) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentSourceCodeKind(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.SourceCodeKind sourceCodeKind) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentSyntaxRoot(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextAndVersion textAndVersion, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentText(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId> documentIds, Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentTextLoader(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader, Microsoft.CodeAnalysis.PreservationMode mode) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithOptions(Microsoft.CodeAnalysis.Options.OptionSet options) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectAnalyzerReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectAssemblyName(Microsoft.CodeAnalysis.ProjectId projectId, string assemblyName) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectCompilationOptions(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.CompilationOptions options) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectCompilationOutputInfo(Microsoft.CodeAnalysis.ProjectId projectId, in Microsoft.CodeAnalysis.CompilationOutputInfo info) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectDefaultNamespace(Microsoft.CodeAnalysis.ProjectId projectId, string defaultNamespace) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectDocumentsOrder(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Immutable.ImmutableList<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectFilePath(Microsoft.CodeAnalysis.ProjectId projectId, string filePath) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectMetadataReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectName(Microsoft.CodeAnalysis.ProjectId projectId, string name) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectOutputFilePath(Microsoft.CodeAnalysis.ProjectId projectId, string outputFilePath) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectOutputRefFilePath(Microsoft.CodeAnalysis.ProjectId projectId, string outputRefFilePath) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectParseOptions(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ParseOptions options) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.Workspace.get -> Microsoft.CodeAnalysis.Workspace
Microsoft.CodeAnalysis.SolutionChanges
Microsoft.CodeAnalysis.SolutionChanges.GetAddedAnalyzerReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.SolutionChanges.GetAddedProjects() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Project>
Microsoft.CodeAnalysis.SolutionChanges.GetProjectChanges() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectChanges>
Microsoft.CodeAnalysis.SolutionChanges.GetRemovedAnalyzerReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.SolutionChanges.GetRemovedProjects() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Project>
Microsoft.CodeAnalysis.SolutionChanges.SolutionChanges() -> void
Microsoft.CodeAnalysis.SolutionId
Microsoft.CodeAnalysis.SolutionId.Equals(Microsoft.CodeAnalysis.SolutionId other) -> bool
Microsoft.CodeAnalysis.SolutionId.Id.get -> System.Guid
Microsoft.CodeAnalysis.SolutionInfo
Microsoft.CodeAnalysis.SolutionInfo.AnalyzerReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.SolutionInfo.FilePath.get -> string
Microsoft.CodeAnalysis.SolutionInfo.Id.get -> Microsoft.CodeAnalysis.SolutionId
Microsoft.CodeAnalysis.SolutionInfo.Projects.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.ProjectInfo>
Microsoft.CodeAnalysis.SolutionInfo.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.Tags.WellKnownTags
Microsoft.CodeAnalysis.TextAndVersion
Microsoft.CodeAnalysis.TextAndVersion.FilePath.get -> string
Microsoft.CodeAnalysis.TextAndVersion.Text.get -> Microsoft.CodeAnalysis.Text.SourceText
Microsoft.CodeAnalysis.TextAndVersion.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.TextDocument.FilePath.get -> string
Microsoft.CodeAnalysis.TextDocument.Folders.get -> System.Collections.Generic.IReadOnlyList<string>
Microsoft.CodeAnalysis.TextDocument.GetTextAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Text.SourceText>
Microsoft.CodeAnalysis.TextDocument.GetTextVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.TextDocument.Id.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.TextDocument.Name.get -> string
Microsoft.CodeAnalysis.TextDocument.Project.get -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.TextDocument.TryGetText(out Microsoft.CodeAnalysis.Text.SourceText text) -> bool
Microsoft.CodeAnalysis.TextDocument.TryGetTextVersion(out Microsoft.CodeAnalysis.VersionStamp version) -> bool
Microsoft.CodeAnalysis.TextDocumentKind
Microsoft.CodeAnalysis.TextDocumentKind.AdditionalDocument = 1 -> Microsoft.CodeAnalysis.TextDocumentKind
Microsoft.CodeAnalysis.TextDocumentKind.AnalyzerConfigDocument = 2 -> Microsoft.CodeAnalysis.TextDocumentKind
Microsoft.CodeAnalysis.TextDocumentKind.Document = 0 -> Microsoft.CodeAnalysis.TextDocumentKind
Microsoft.CodeAnalysis.TextLoader
Microsoft.CodeAnalysis.TextLoader.TextLoader() -> void
Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.VersionStamp.Equals(Microsoft.CodeAnalysis.VersionStamp version) -> bool
Microsoft.CodeAnalysis.VersionStamp.GetNewerVersion() -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.VersionStamp.GetNewerVersion(Microsoft.CodeAnalysis.VersionStamp version) -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.VersionStamp.VersionStamp() -> void
Microsoft.CodeAnalysis.Workspace
Microsoft.CodeAnalysis.Workspace.CheckAdditionalDocumentIsInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckAdditionalDocumentIsNotInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckAnalyzerConfigDocumentIsInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckAnalyzerConfigDocumentIsNotInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckCanOpenDocuments() -> void
Microsoft.CodeAnalysis.Workspace.CheckDocumentIsClosed(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckDocumentIsInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckDocumentIsNotInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckDocumentIsOpen(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotContainOpenDocuments(Microsoft.CodeAnalysis.ProjectId projectId) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotHaveAnalyzerReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotHaveMetadataReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotHaveProjectReference(Microsoft.CodeAnalysis.ProjectId fromProjectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotHaveTransitiveProjectReference(Microsoft.CodeAnalysis.ProjectId fromProjectId, Microsoft.CodeAnalysis.ProjectId toProjectId) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectHasAnalyzerReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectHasMetadataReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectHasProjectReference(Microsoft.CodeAnalysis.ProjectId fromProjectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectIsInCurrentSolution(Microsoft.CodeAnalysis.ProjectId projectId) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectIsNotInCurrentSolution(Microsoft.CodeAnalysis.ProjectId projectId) -> void
Microsoft.CodeAnalysis.Workspace.CheckSolutionIsEmpty() -> void
Microsoft.CodeAnalysis.Workspace.ClearOpenDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.ClearOpenDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool isSolutionClosing) -> void
Microsoft.CodeAnalysis.Workspace.ClearSolution() -> void
Microsoft.CodeAnalysis.Workspace.CreateSolution(Microsoft.CodeAnalysis.SolutionId id) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Workspace.CreateSolution(Microsoft.CodeAnalysis.SolutionInfo solutionInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Workspace.CurrentSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Workspace.Dispose() -> void
Microsoft.CodeAnalysis.Workspace.DocumentActiveContextChanged -> System.EventHandler<Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs>
Microsoft.CodeAnalysis.Workspace.DocumentClosed -> System.EventHandler<Microsoft.CodeAnalysis.DocumentEventArgs>
Microsoft.CodeAnalysis.Workspace.DocumentOpened -> System.EventHandler<Microsoft.CodeAnalysis.DocumentEventArgs>
Microsoft.CodeAnalysis.Workspace.Kind.get -> string
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentClosed(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader reloader) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentOpened(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer, bool isCurrentContext = true) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText newText, Microsoft.CodeAnalysis.PreservationMode mode) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentTextLoaderChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentClosed(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader reloader) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentOpened(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer, bool isCurrentContext = true) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText newText, Microsoft.CodeAnalysis.PreservationMode mode) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentTextLoaderChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
Microsoft.CodeAnalysis.Workspace.OnAssemblyNameChanged(Microsoft.CodeAnalysis.ProjectId projectId, string assemblyName) -> void
Microsoft.CodeAnalysis.Workspace.OnCompilationOptionsChanged(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.CompilationOptions options) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentClosed(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader reloader, bool updateActiveContext = false) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentContextUpdated(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentInfoChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.DocumentInfo newInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentOpened(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer, bool isCurrentContext = true) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentReloaded(Microsoft.CodeAnalysis.DocumentInfo newDocumentInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentsAdded(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentInfo> documentInfos) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentSourceCodeKindChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.SourceCodeKind sourceCodeKind) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText newText, Microsoft.CodeAnalysis.PreservationMode mode) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentTextLoaderChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader) -> void
Microsoft.CodeAnalysis.Workspace.OnMetadataReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
Microsoft.CodeAnalysis.Workspace.OnMetadataReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
Microsoft.CodeAnalysis.Workspace.OnOutputFilePathChanged(Microsoft.CodeAnalysis.ProjectId projectId, string outputFilePath) -> void
Microsoft.CodeAnalysis.Workspace.OnOutputRefFilePathChanged(Microsoft.CodeAnalysis.ProjectId projectId, string outputFilePath) -> void
Microsoft.CodeAnalysis.Workspace.OnParseOptionsChanged(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ParseOptions options) -> void
Microsoft.CodeAnalysis.Workspace.OnProjectAdded(Microsoft.CodeAnalysis.ProjectInfo projectInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnProjectNameChanged(Microsoft.CodeAnalysis.ProjectId projectId, string name, string filePath) -> void
Microsoft.CodeAnalysis.Workspace.OnProjectReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
Microsoft.CodeAnalysis.Workspace.OnProjectReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
Microsoft.CodeAnalysis.Workspace.OnSolutionAdded(Microsoft.CodeAnalysis.SolutionInfo solutionInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnSolutionReloaded(Microsoft.CodeAnalysis.SolutionInfo reloadedSolutionInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnSolutionRemoved() -> void
Microsoft.CodeAnalysis.Workspace.Options.get -> Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Workspace.Options.set -> void
Microsoft.CodeAnalysis.Workspace.RaiseDocumentActiveContextChangedEventAsync(Microsoft.CodeAnalysis.Document document) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RaiseDocumentActiveContextChangedEventAsync(Microsoft.CodeAnalysis.Text.SourceTextContainer sourceTextContainer, Microsoft.CodeAnalysis.DocumentId oldActiveContextDocumentId, Microsoft.CodeAnalysis.DocumentId newActiveContextDocumentId) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RaiseDocumentClosedEventAsync(Microsoft.CodeAnalysis.Document document) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RaiseDocumentOpenedEventAsync(Microsoft.CodeAnalysis.Document document) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RaiseWorkspaceChangedEventAsync(Microsoft.CodeAnalysis.WorkspaceChangeKind kind, Microsoft.CodeAnalysis.Solution oldSolution, Microsoft.CodeAnalysis.Solution newSolution, Microsoft.CodeAnalysis.ProjectId projectId = null, Microsoft.CodeAnalysis.DocumentId documentId = null) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RegisterText(Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer) -> void
Microsoft.CodeAnalysis.Workspace.ScheduleTask(System.Action action, string taskName = "Workspace.Task") -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.ScheduleTask<T>(System.Func<T> func, string taskName = "Workspace.Task") -> System.Threading.Tasks.Task<T>
Microsoft.CodeAnalysis.Workspace.Services.get -> Microsoft.CodeAnalysis.Host.HostWorkspaceServices
Microsoft.CodeAnalysis.Workspace.SetCurrentSolution(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Workspace.UnregisterText(Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer) -> void
Microsoft.CodeAnalysis.Workspace.UpdateReferencesAfterAdd() -> void
Microsoft.CodeAnalysis.Workspace.Workspace(Microsoft.CodeAnalysis.Host.HostServices host, string workspaceKind) -> void
Microsoft.CodeAnalysis.Workspace.WorkspaceChanged -> System.EventHandler<Microsoft.CodeAnalysis.WorkspaceChangeEventArgs>
Microsoft.CodeAnalysis.Workspace.WorkspaceFailed -> System.EventHandler<Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs>
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.DocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.Kind.get -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.NewSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.OldSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.WorkspaceChangeEventArgs(Microsoft.CodeAnalysis.WorkspaceChangeKind kind, Microsoft.CodeAnalysis.Solution oldSolution, Microsoft.CodeAnalysis.Solution newSolution, Microsoft.CodeAnalysis.ProjectId projectId = null, Microsoft.CodeAnalysis.DocumentId documentId = null) -> void
Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AdditionalDocumentAdded = 13 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AdditionalDocumentChanged = 16 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AdditionalDocumentReloaded = 15 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AdditionalDocumentRemoved = 14 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AnalyzerConfigDocumentAdded = 18 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AnalyzerConfigDocumentChanged = 21 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AnalyzerConfigDocumentReloaded = 20 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AnalyzerConfigDocumentRemoved = 19 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentAdded = 9 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentChanged = 12 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentInfoChanged = 17 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentReloaded = 11 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentRemoved = 10 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.ProjectAdded = 5 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.ProjectChanged = 7 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.ProjectReloaded = 8 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.ProjectRemoved = 6 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionAdded = 1 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionChanged = 0 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionCleared = 3 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionReloaded = 4 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionRemoved = 2 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceDiagnostic
Microsoft.CodeAnalysis.WorkspaceDiagnostic.Kind.get -> Microsoft.CodeAnalysis.WorkspaceDiagnosticKind
Microsoft.CodeAnalysis.WorkspaceDiagnostic.Message.get -> string
Microsoft.CodeAnalysis.WorkspaceDiagnostic.WorkspaceDiagnostic(Microsoft.CodeAnalysis.WorkspaceDiagnosticKind kind, string message) -> void
Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs
Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs.Diagnostic.get -> Microsoft.CodeAnalysis.WorkspaceDiagnostic
Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs.WorkspaceDiagnosticEventArgs(Microsoft.CodeAnalysis.WorkspaceDiagnostic diagnostic) -> void
Microsoft.CodeAnalysis.WorkspaceDiagnosticKind
Microsoft.CodeAnalysis.WorkspaceDiagnosticKind.Failure = 0 -> Microsoft.CodeAnalysis.WorkspaceDiagnosticKind
Microsoft.CodeAnalysis.WorkspaceDiagnosticKind.Warning = 1 -> Microsoft.CodeAnalysis.WorkspaceDiagnosticKind
Microsoft.CodeAnalysis.WorkspaceKind
Microsoft.CodeAnalysis.WorkspaceRegistration
Microsoft.CodeAnalysis.WorkspaceRegistration.Workspace.get -> Microsoft.CodeAnalysis.Workspace
Microsoft.CodeAnalysis.WorkspaceRegistration.WorkspaceChanged -> System.EventHandler
Microsoft.CodeAnalysis.XmlDocumentationProvider
Microsoft.CodeAnalysis.XmlDocumentationProvider.XmlDocumentationProvider() -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.CanApplyChange(Microsoft.CodeAnalysis.ApplyChangesKind feature) -> bool
override Microsoft.CodeAnalysis.AdhocWorkspace.CanOpenDocuments.get -> bool
override Microsoft.CodeAnalysis.AdhocWorkspace.CloseAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.CloseAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.CloseDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.OpenAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.OpenAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.OpenDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
override Microsoft.CodeAnalysis.Classification.ClassifiedSpan.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Classification.ClassifiedSpan.GetHashCode() -> int
override Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation.Apply(Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken) -> void
override Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.ComputeOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
override Microsoft.CodeAnalysis.CodeActions.OpenDocumentOperation.Apply(Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken) -> void
override Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.GetHashCode() -> int
override Microsoft.CodeAnalysis.CodeStyle.NotificationOption.ToString() -> string
override Microsoft.CodeAnalysis.CompilationOutputInfo.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.CompilationOutputInfo.GetHashCode() -> int
override Microsoft.CodeAnalysis.Differencing.Edit<TNode>.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Differencing.Edit<TNode>.GetHashCode() -> int
override Microsoft.CodeAnalysis.DocumentId.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.DocumentId.GetHashCode() -> int
override Microsoft.CodeAnalysis.DocumentId.ToString() -> string
override Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Editing.DeclarationModifiers.GetHashCode() -> int
override Microsoft.CodeAnalysis.Editing.DeclarationModifiers.ToString() -> string
override Microsoft.CodeAnalysis.FileTextLoader.LoadTextAndVersionAsync(Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.DocumentId documentId, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.TextAndVersion>
override Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.GetHashCode() -> int
override Microsoft.CodeAnalysis.Host.Mef.MefHostServices.CreateWorkspaceServices(Microsoft.CodeAnalysis.Workspace workspace) -> Microsoft.CodeAnalysis.Host.HostWorkspaceServices
override Microsoft.CodeAnalysis.Options.DocumentOptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.OptionKey optionAndLanguage, object value) -> Microsoft.CodeAnalysis.Options.OptionSet
override Microsoft.CodeAnalysis.Options.Option<T>.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Options.Option<T>.GetHashCode() -> int
override Microsoft.CodeAnalysis.Options.Option<T>.ToString() -> string
override Microsoft.CodeAnalysis.Options.OptionKey.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Options.OptionKey.GetHashCode() -> int
override Microsoft.CodeAnalysis.Options.OptionKey.ToString() -> string
override Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.GetHashCode() -> int
override Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.ToString() -> string
override Microsoft.CodeAnalysis.ProjectId.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.ProjectId.GetHashCode() -> int
override Microsoft.CodeAnalysis.ProjectId.ToString() -> string
override Microsoft.CodeAnalysis.ProjectReference.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.ProjectReference.GetHashCode() -> int
override Microsoft.CodeAnalysis.SolutionId.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.SolutionId.GetHashCode() -> int
override Microsoft.CodeAnalysis.VersionStamp.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.VersionStamp.GetHashCode() -> int
override Microsoft.CodeAnalysis.VersionStamp.ToString() -> string
override Microsoft.CodeAnalysis.WorkspaceDiagnostic.ToString() -> string
override Microsoft.CodeAnalysis.XmlDocumentationProvider.GetDocumentationForSymbol(string documentationMemberID, System.Globalization.CultureInfo preferredCulture, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> string
static Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.AdditiveTypeNames.get -> System.Collections.Immutable.ImmutableArray<string>
static Microsoft.CodeAnalysis.Classification.Classifier.GetClassifiedSpans(Microsoft.CodeAnalysis.SemanticModel semanticModel, Microsoft.CodeAnalysis.Text.TextSpan textSpan, Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Classification.ClassifiedSpan>
static Microsoft.CodeAnalysis.Classification.Classifier.GetClassifiedSpansAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan textSpan, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Classification.ClassifiedSpan>>
static Microsoft.CodeAnalysis.CodeActions.CodeAction.Create(string title, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeActions.CodeAction> nestedActions, bool isInlinable) -> Microsoft.CodeAnalysis.CodeActions.CodeAction
static Microsoft.CodeAnalysis.CodeActions.CodeAction.Create(string title, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>> createChangedDocument, string equivalenceKey = null) -> Microsoft.CodeAnalysis.CodeActions.CodeAction
static Microsoft.CodeAnalysis.CodeActions.CodeAction.Create(string title, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>> createChangedSolution, string equivalenceKey = null) -> Microsoft.CodeAnalysis.CodeActions.CodeAction
static Microsoft.CodeAnalysis.CodeActions.ConflictAnnotation.Create(string description) -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.CodeActions.ConflictAnnotation.GetDescription(Microsoft.CodeAnalysis.SyntaxAnnotation annotation) -> string
static Microsoft.CodeAnalysis.CodeActions.RenameAnnotation.Create() -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.CodeActions.WarningAnnotation.Create(string description) -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.CodeActions.WarningAnnotation.GetDescription(Microsoft.CodeAnalysis.SyntaxAnnotation annotation) -> string
static Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders.BatchFixer.get -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
static Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Default.get -> Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>
static Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.FromXElement(System.Xml.Linq.XElement element) -> Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>
static Microsoft.CodeAnalysis.CompilationOutputInfo.operator !=(in Microsoft.CodeAnalysis.CompilationOutputInfo left, in Microsoft.CodeAnalysis.CompilationOutputInfo right) -> bool
static Microsoft.CodeAnalysis.CompilationOutputInfo.operator ==(in Microsoft.CodeAnalysis.CompilationOutputInfo left, in Microsoft.CodeAnalysis.CompilationOutputInfo right) -> bool
static Microsoft.CodeAnalysis.DocumentId.CreateFromSerialized(Microsoft.CodeAnalysis.ProjectId projectId, System.Guid id, string debugName = null) -> Microsoft.CodeAnalysis.DocumentId
static Microsoft.CodeAnalysis.DocumentId.CreateNewId(Microsoft.CodeAnalysis.ProjectId projectId, string debugName = null) -> Microsoft.CodeAnalysis.DocumentId
static Microsoft.CodeAnalysis.DocumentId.operator !=(Microsoft.CodeAnalysis.DocumentId left, Microsoft.CodeAnalysis.DocumentId right) -> bool
static Microsoft.CodeAnalysis.DocumentId.operator ==(Microsoft.CodeAnalysis.DocumentId left, Microsoft.CodeAnalysis.DocumentId right) -> bool
static Microsoft.CodeAnalysis.DocumentInfo.Create(Microsoft.CodeAnalysis.DocumentId id, string name, System.Collections.Generic.IEnumerable<string> folders = null, Microsoft.CodeAnalysis.SourceCodeKind sourceCodeKind = Microsoft.CodeAnalysis.SourceCodeKind.Regular, Microsoft.CodeAnalysis.TextLoader loader = null, string filePath = null, bool isGenerated = false) -> Microsoft.CodeAnalysis.DocumentInfo
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Abstract.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Async.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Const.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Extern.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.From(Microsoft.CodeAnalysis.ISymbol symbol) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.New.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.None.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator !=(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> bool
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator &(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator +(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator -(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator ==(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> bool
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator |(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Override.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Partial.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.ReadOnly.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Ref.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Sealed.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Static.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.TryParse(string value, out Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> bool
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Unsafe.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Virtual.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Volatile.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithEvents.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WriteOnly.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DocumentEditor.CreateAsync(Microsoft.CodeAnalysis.Document document, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Editing.DocumentEditor>
static Microsoft.CodeAnalysis.Editing.ImportAdder.AddImportsAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Editing.ImportAdder.AddImportsAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.SyntaxAnnotation annotation, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Editing.ImportAdder.AddImportsAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Editing.ImportAdder.AddImportsAsync(Microsoft.CodeAnalysis.Document document, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Editing.SymbolEditor.Create(Microsoft.CodeAnalysis.Document document) -> Microsoft.CodeAnalysis.Editing.SymbolEditor
static Microsoft.CodeAnalysis.Editing.SymbolEditor.Create(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.Editing.SymbolEditor
static Microsoft.CodeAnalysis.Editing.SymbolEditorExtensions.GetBaseOrInterfaceDeclarationReferenceAsync(this Microsoft.CodeAnalysis.Editing.SymbolEditor editor, Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.ITypeSymbol baseOrInterfaceType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxNode>
static Microsoft.CodeAnalysis.Editing.SymbolEditorExtensions.SetBaseTypeAsync(this Microsoft.CodeAnalysis.Editing.SymbolEditor editor, Microsoft.CodeAnalysis.INamedTypeSymbol symbol, Microsoft.CodeAnalysis.ITypeSymbol newBaseType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.Editing.SymbolEditorExtensions.SetBaseTypeAsync(this Microsoft.CodeAnalysis.Editing.SymbolEditor editor, Microsoft.CodeAnalysis.INamedTypeSymbol symbol, System.Func<Microsoft.CodeAnalysis.Editing.SyntaxGenerator, Microsoft.CodeAnalysis.SyntaxNode> getNewBaseType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddAttribute(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode attribute) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddAttributeArgument(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode attributeDeclaration, Microsoft.CodeAnalysis.SyntaxNode attributeArgument) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddBaseType(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode baseType) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddInterfaceType(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddMember(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode member) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddParameter(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode parameter) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddReturnAttribute(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode attribute) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.InsertMembers(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.InsertParameter(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, int index, Microsoft.CodeAnalysis.SyntaxNode parameter) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetAccessibility(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Accessibility accessibility) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetExpression(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode expression) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetGetAccessorStatements(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetModifiers(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetName(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, string name) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetSetAccessorStatements(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetStatements(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetType(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode type) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetTypeConstraint(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, string typeParameterName, Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind kind, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> types) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetTypeParameters(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<string> typeParameters) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DefaultRemoveOptions -> Microsoft.CodeAnalysis.SyntaxRemoveOptions
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGenerator(Microsoft.CodeAnalysis.Document document) -> Microsoft.CodeAnalysis.Editing.SyntaxGenerator
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGenerator(Microsoft.CodeAnalysis.Project project) -> Microsoft.CodeAnalysis.Editing.SyntaxGenerator
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGenerator(Microsoft.CodeAnalysis.Workspace workspace, string language) -> Microsoft.CodeAnalysis.Editing.SyntaxGenerator
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.PreserveTrivia<TNode>(TNode node, System.Func<TNode, Microsoft.CodeAnalysis.SyntaxNode> nodeChanger) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveRange<TNode>(Microsoft.CodeAnalysis.SeparatedSyntaxList<TNode> list, int offset, int count) -> Microsoft.CodeAnalysis.SeparatedSyntaxList<TNode>
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveRange<TNode>(Microsoft.CodeAnalysis.SyntaxList<TNode> list, int offset, int count) -> Microsoft.CodeAnalysis.SyntaxList<TNode>
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceRange(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> replacements) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceWithTrivia(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode original, Microsoft.CodeAnalysis.SyntaxNode replacement) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceWithTrivia(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxToken original, Microsoft.CodeAnalysis.SyntaxToken replacement) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceWithTrivia<TNode>(Microsoft.CodeAnalysis.SyntaxNode root, TNode original, System.Func<TNode, Microsoft.CodeAnalysis.SyntaxNode> replacer) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.operator !=(Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation left, Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation right) -> bool
static Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.operator ==(Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation left, Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation right) -> bool
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindCallersAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Document> documents, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindCallersAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDeclarationsAsync(Microsoft.CodeAnalysis.Project project, string name, bool ignoreCase, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDeclarationsAsync(Microsoft.CodeAnalysis.Project project, string name, bool ignoreCase, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDerivedClassesAsync(Microsoft.CodeAnalysis.INamedTypeSymbol type, Microsoft.CodeAnalysis.Solution solution, bool transitive = true, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.INamedTypeSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDerivedClassesAsync(Microsoft.CodeAnalysis.INamedTypeSymbol type, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.INamedTypeSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDerivedInterfacesAsync(Microsoft.CodeAnalysis.INamedTypeSymbol type, Microsoft.CodeAnalysis.Solution solution, bool transitive = true, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.INamedTypeSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindImplementationsAsync(Microsoft.CodeAnalysis.INamedTypeSymbol type, Microsoft.CodeAnalysis.Solution solution, bool transitive = true, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.INamedTypeSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindImplementationsAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindImplementedInterfaceMembersAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindOverridesAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindReferencesAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress progress, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Document> documents, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindReferencesAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Document> documents, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindReferencesAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSimilarSymbols<TSymbol>(TSymbol symbol, Microsoft.CodeAnalysis.Compilation compilation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<TSymbol>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Project project, string name, bool ignoreCase, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Project project, string name, bool ignoreCase, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Project project, System.Func<string, bool> predicate, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Project project, System.Func<string, bool> predicate, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Solution solution, string name, bool ignoreCase, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Solution solution, string name, bool ignoreCase, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Solution solution, System.Func<string, bool> predicate, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Solution solution, System.Func<string, bool> predicate, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsWithPatternAsync(Microsoft.CodeAnalysis.Project project, string pattern, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsWithPatternAsync(Microsoft.CodeAnalysis.Project project, string pattern, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsWithPatternAsync(Microsoft.CodeAnalysis.Solution solution, string pattern, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsWithPatternAsync(Microsoft.CodeAnalysis.Solution solution, string pattern, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDefinitionAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSymbolAtPosition(Microsoft.CodeAnalysis.SemanticModel semanticModel, int position, Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.ISymbol
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSymbolAtPositionAsync(Microsoft.CodeAnalysis.Document document, int position, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSymbolAtPositionAsync(Microsoft.CodeAnalysis.SemanticModel semanticModel, int position, Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.Formatting.Formatter.Annotation.get -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxAnnotation annotation, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.SyntaxAnnotation annotation, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(Microsoft.CodeAnalysis.Document document, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IList<Microsoft.CodeAnalysis.Text.TextChange>
static Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IList<Microsoft.CodeAnalysis.Text.TextChange>
static Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IList<Microsoft.CodeAnalysis.Text.TextChange>
static Microsoft.CodeAnalysis.Formatting.Formatter.OrganizeImportsAsync(Microsoft.CodeAnalysis.Document document, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<int>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<string>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<int>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create(System.Collections.Generic.IEnumerable<System.Reflection.Assembly> assemblies) -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices
static Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create(System.Composition.CompositionContext compositionContext) -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices
static Microsoft.CodeAnalysis.Host.Mef.MefHostServices.DefaultAssemblies.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Assembly>
static Microsoft.CodeAnalysis.Host.Mef.MefHostServices.DefaultHost.get -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices
static Microsoft.CodeAnalysis.Options.Option<T>.implicit operator Microsoft.CodeAnalysis.Options.OptionKey(Microsoft.CodeAnalysis.Options.Option<T> option) -> Microsoft.CodeAnalysis.Options.OptionKey
static Microsoft.CodeAnalysis.Options.OptionKey.operator !=(Microsoft.CodeAnalysis.Options.OptionKey left, Microsoft.CodeAnalysis.Options.OptionKey right) -> bool
static Microsoft.CodeAnalysis.Options.OptionKey.operator ==(Microsoft.CodeAnalysis.Options.OptionKey left, Microsoft.CodeAnalysis.Options.OptionKey right) -> bool
static Microsoft.CodeAnalysis.ProjectId.CreateFromSerialized(System.Guid id, string debugName = null) -> Microsoft.CodeAnalysis.ProjectId
static Microsoft.CodeAnalysis.ProjectId.CreateNewId(string debugName = null) -> Microsoft.CodeAnalysis.ProjectId
static Microsoft.CodeAnalysis.ProjectId.operator !=(Microsoft.CodeAnalysis.ProjectId left, Microsoft.CodeAnalysis.ProjectId right) -> bool
static Microsoft.CodeAnalysis.ProjectId.operator ==(Microsoft.CodeAnalysis.ProjectId left, Microsoft.CodeAnalysis.ProjectId right) -> bool
static Microsoft.CodeAnalysis.ProjectInfo.Create(Microsoft.CodeAnalysis.ProjectId id, Microsoft.CodeAnalysis.VersionStamp version, string name, string assemblyName, string language, string filePath = null, string outputFilePath = null, Microsoft.CodeAnalysis.CompilationOptions compilationOptions = null, Microsoft.CodeAnalysis.ParseOptions parseOptions = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> documents = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> additionalDocuments = null, bool isSubmission = false, System.Type hostObjectType = null, string outputRefFilePath = null) -> Microsoft.CodeAnalysis.ProjectInfo
static Microsoft.CodeAnalysis.ProjectInfo.Create(Microsoft.CodeAnalysis.ProjectId id, Microsoft.CodeAnalysis.VersionStamp version, string name, string assemblyName, string language, string filePath, string outputFilePath, Microsoft.CodeAnalysis.CompilationOptions compilationOptions, Microsoft.CodeAnalysis.ParseOptions parseOptions, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> documents, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> additionalDocuments, bool isSubmission, System.Type hostObjectType) -> Microsoft.CodeAnalysis.ProjectInfo
static Microsoft.CodeAnalysis.ProjectReference.operator !=(Microsoft.CodeAnalysis.ProjectReference left, Microsoft.CodeAnalysis.ProjectReference right) -> bool
static Microsoft.CodeAnalysis.ProjectReference.operator ==(Microsoft.CodeAnalysis.ProjectReference left, Microsoft.CodeAnalysis.ProjectReference right) -> bool
static Microsoft.CodeAnalysis.Recommendations.RecommendationOptions.FilterOutOfScopeLocals.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Recommendations.RecommendationOptions.HideAdvancedMembers.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Recommendations.Recommender.GetRecommendedSymbolsAtPosition(Microsoft.CodeAnalysis.SemanticModel semanticModel, int position, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.Recommendations.Recommender.GetRecommendedSymbolsAtPositionAsync(Microsoft.CodeAnalysis.SemanticModel semanticModel, int position, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.Rename.RenameOptions.PreviewChanges.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Rename.RenameOptions.RenameInComments.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Rename.RenameOptions.RenameInStrings.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Rename.RenameOptions.RenameOverloads.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAsync(Microsoft.CodeAnalysis.Document document, string newDocumentName, System.Collections.Generic.IReadOnlyList<string> newDocumentFolders = null, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet>
static Microsoft.CodeAnalysis.Rename.Renamer.RenameSymbolAsync(Microsoft.CodeAnalysis.Solution solution, Microsoft.CodeAnalysis.ISymbol symbol, string newName, Microsoft.CodeAnalysis.Options.OptionSet optionSet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.AllowSimplificationToBaseType.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.AllowSimplificationToGenericType.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferAliasToQualification.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferImplicitTypeInference.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferImplicitTypeInLocalDeclaration.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferOmittingModuleNamesInQualification.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyEventAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyFieldAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyMemberAccessWithThisOrMe.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyMethodAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyPropertyAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.Simplifier.AddImportsAnnotation.get -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.Simplification.Simplifier.Annotation.get -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.Simplification.Simplifier.Expand(Microsoft.CodeAnalysis.SyntaxToken token, Microsoft.CodeAnalysis.SemanticModel semanticModel, Microsoft.CodeAnalysis.Workspace workspace, System.Func<Microsoft.CodeAnalysis.SyntaxNode, bool> expandInsideNode = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxToken
static Microsoft.CodeAnalysis.Simplification.Simplifier.Expand<TNode>(TNode node, Microsoft.CodeAnalysis.SemanticModel semanticModel, Microsoft.CodeAnalysis.Workspace workspace, System.Func<Microsoft.CodeAnalysis.SyntaxNode, bool> expandInsideNode = null, bool expandParameter = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> TNode
static Microsoft.CodeAnalysis.Simplification.Simplifier.ExpandAsync(Microsoft.CodeAnalysis.SyntaxToken token, Microsoft.CodeAnalysis.Document document, System.Func<Microsoft.CodeAnalysis.SyntaxNode, bool> expandInsideNode = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxToken>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ExpandAsync<TNode>(TNode node, Microsoft.CodeAnalysis.Document document, System.Func<Microsoft.CodeAnalysis.SyntaxNode, bool> expandInsideNode = null, bool expandParameter = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<TNode>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.SyntaxAnnotation annotation, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document document, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Simplification.Simplifier.SpecialTypeAnnotation.get -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.SolutionId.CreateFromSerialized(System.Guid id, string debugName = null) -> Microsoft.CodeAnalysis.SolutionId
static Microsoft.CodeAnalysis.SolutionId.CreateNewId(string debugName = null) -> Microsoft.CodeAnalysis.SolutionId
static Microsoft.CodeAnalysis.SolutionId.operator !=(Microsoft.CodeAnalysis.SolutionId left, Microsoft.CodeAnalysis.SolutionId right) -> bool
static Microsoft.CodeAnalysis.SolutionId.operator ==(Microsoft.CodeAnalysis.SolutionId left, Microsoft.CodeAnalysis.SolutionId right) -> bool
static Microsoft.CodeAnalysis.SolutionInfo.Create(Microsoft.CodeAnalysis.SolutionId id, Microsoft.CodeAnalysis.VersionStamp version, string filePath = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectInfo> projects = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences = null) -> Microsoft.CodeAnalysis.SolutionInfo
static Microsoft.CodeAnalysis.SolutionInfo.Create(Microsoft.CodeAnalysis.SolutionId id, Microsoft.CodeAnalysis.VersionStamp version, string filePath, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectInfo> projects) -> Microsoft.CodeAnalysis.SolutionInfo
static Microsoft.CodeAnalysis.TextAndVersion.Create(Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.VersionStamp version, string filePath = null) -> Microsoft.CodeAnalysis.TextAndVersion
static Microsoft.CodeAnalysis.TextLoader.From(Microsoft.CodeAnalysis.Text.SourceTextContainer container, Microsoft.CodeAnalysis.VersionStamp version, string filePath = null) -> Microsoft.CodeAnalysis.TextLoader
static Microsoft.CodeAnalysis.TextLoader.From(Microsoft.CodeAnalysis.TextAndVersion textAndVersion) -> Microsoft.CodeAnalysis.TextLoader
static Microsoft.CodeAnalysis.VersionStamp.Create() -> Microsoft.CodeAnalysis.VersionStamp
static Microsoft.CodeAnalysis.VersionStamp.Create(System.DateTime utcTimeLastModified) -> Microsoft.CodeAnalysis.VersionStamp
static Microsoft.CodeAnalysis.VersionStamp.Default.get -> Microsoft.CodeAnalysis.VersionStamp
static Microsoft.CodeAnalysis.VersionStamp.operator !=(Microsoft.CodeAnalysis.VersionStamp left, Microsoft.CodeAnalysis.VersionStamp right) -> bool
static Microsoft.CodeAnalysis.VersionStamp.operator ==(Microsoft.CodeAnalysis.VersionStamp left, Microsoft.CodeAnalysis.VersionStamp right) -> bool
static Microsoft.CodeAnalysis.Workspace.GetWorkspaceRegistration(Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer) -> Microsoft.CodeAnalysis.WorkspaceRegistration
static Microsoft.CodeAnalysis.Workspace.TryGetWorkspace(Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer, out Microsoft.CodeAnalysis.Workspace workspace) -> bool
static Microsoft.CodeAnalysis.XmlDocumentationProvider.CreateFromBytes(byte[] xmlDocCommentBytes) -> Microsoft.CodeAnalysis.XmlDocumentationProvider
static Microsoft.CodeAnalysis.XmlDocumentationProvider.CreateFromFile(string xmlDocCommentFilePath) -> Microsoft.CodeAnalysis.XmlDocumentationProvider
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.QualifyEventAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.QualifyFieldAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.QualifyMethodAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.QualifyPropertyAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Error -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.None -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Silent -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Suggestion -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Warning -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputePreviewOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.EquivalenceKey.get -> string
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedDocumentAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessChangesAsync(Microsoft.CodeAnalysis.Document document, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.Tags.get -> System.Collections.Immutable.ImmutableArray<string>
virtual Microsoft.CodeAnalysis.CodeActions.CodeActionOperation.Apply(Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken) -> void
virtual Microsoft.CodeAnalysis.CodeActions.CodeActionOperation.Title.get -> string
virtual Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
virtual Microsoft.CodeAnalysis.CodeFixes.FixAllProvider.GetSupportedFixAllDiagnosticIds(Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider originalCodeFixProvider) -> System.Collections.Generic.IEnumerable<string>
virtual Microsoft.CodeAnalysis.CodeFixes.FixAllProvider.GetSupportedFixAllScopes() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeFixes.FixAllScope>
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertNodesAfter(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> newDeclarations) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertNodesBefore(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> newDeclarations) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MemberAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode memberName) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.OperatorDeclaration(Microsoft.CodeAnalysis.Editing.OperatorKind kind, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, Microsoft.CodeAnalysis.SyntaxNode returnType = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveNode(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveNode(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxRemoveOptions options) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceNode(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxNode newDeclaration) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.FileTextLoader.CreateText(System.IO.Stream stream, Microsoft.CodeAnalysis.Workspace workspace) -> Microsoft.CodeAnalysis.Text.SourceText
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetLanguageServices(string languageName) -> Microsoft.CodeAnalysis.Host.HostLanguageServices
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.IsSupported(string languageName) -> bool
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.PersistentStorage.get -> Microsoft.CodeAnalysis.Host.IPersistentStorageService
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.SupportedLanguages.get -> System.Collections.Generic.IEnumerable<string>
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.TemporaryStorage.get -> Microsoft.CodeAnalysis.Host.ITemporaryStorageService
virtual Microsoft.CodeAnalysis.Workspace.AdjustReloadedProject(Microsoft.CodeAnalysis.Project oldProject, Microsoft.CodeAnalysis.Project reloadedProject) -> Microsoft.CodeAnalysis.Project
virtual Microsoft.CodeAnalysis.Workspace.AdjustReloadedSolution(Microsoft.CodeAnalysis.Solution oldSolution, Microsoft.CodeAnalysis.Solution reloadedSolution) -> Microsoft.CodeAnalysis.Solution
virtual Microsoft.CodeAnalysis.Workspace.ApplyAdditionalDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo info, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAdditionalDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAdditionalDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId id, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerConfigDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo info, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerConfigDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerConfigDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId id, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyCompilationOptionsChanged(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.CompilationOptions options) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo info, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyDocumentInfoChanged(Microsoft.CodeAnalysis.DocumentId id, Microsoft.CodeAnalysis.DocumentInfo info) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId id, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyMetadataReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyMetadataReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyParseOptionsChanged(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ParseOptions options) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectAdded(Microsoft.CodeAnalysis.ProjectInfo project) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectChanges(Microsoft.CodeAnalysis.ProjectChanges projectChanges) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectRemoved(Microsoft.CodeAnalysis.ProjectId projectId) -> void
virtual Microsoft.CodeAnalysis.Workspace.CanApplyChange(Microsoft.CodeAnalysis.ApplyChangesKind feature) -> bool
virtual Microsoft.CodeAnalysis.Workspace.CanApplyCompilationOptionChange(Microsoft.CodeAnalysis.CompilationOptions oldOptions, Microsoft.CodeAnalysis.CompilationOptions newOptions, Microsoft.CodeAnalysis.Project project) -> bool
virtual Microsoft.CodeAnalysis.Workspace.CanApplyParseOptionChange(Microsoft.CodeAnalysis.ParseOptions oldOptions, Microsoft.CodeAnalysis.ParseOptions newOptions, Microsoft.CodeAnalysis.Project project) -> bool
virtual Microsoft.CodeAnalysis.Workspace.CanOpenDocuments.get -> bool
virtual Microsoft.CodeAnalysis.Workspace.CheckDocumentCanBeRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.CheckProjectCanBeRemoved(Microsoft.CodeAnalysis.ProjectId projectId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ClearDocumentData(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ClearProjectData(Microsoft.CodeAnalysis.ProjectId projectId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ClearSolutionData() -> void
virtual Microsoft.CodeAnalysis.Workspace.CloseAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.CloseAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.CloseDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.Dispose(bool finalize) -> void
virtual Microsoft.CodeAnalysis.Workspace.GetAdditionalDocumentName(Microsoft.CodeAnalysis.DocumentId documentId) -> string
virtual Microsoft.CodeAnalysis.Workspace.GetAnalyzerConfigDocumentName(Microsoft.CodeAnalysis.DocumentId documentId) -> string
virtual Microsoft.CodeAnalysis.Workspace.GetDocumentIdInCurrentContext(Microsoft.CodeAnalysis.Text.SourceTextContainer container) -> Microsoft.CodeAnalysis.DocumentId
virtual Microsoft.CodeAnalysis.Workspace.GetDocumentName(Microsoft.CodeAnalysis.DocumentId documentId) -> string
virtual Microsoft.CodeAnalysis.Workspace.GetOpenDocumentIds(Microsoft.CodeAnalysis.ProjectId projectId = null) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
virtual Microsoft.CodeAnalysis.Workspace.GetProjectName(Microsoft.CodeAnalysis.ProjectId projectId) -> string
virtual Microsoft.CodeAnalysis.Workspace.GetRelatedDocumentIds(Microsoft.CodeAnalysis.Text.SourceTextContainer container) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
virtual Microsoft.CodeAnalysis.Workspace.IsDocumentOpen(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
virtual Microsoft.CodeAnalysis.Workspace.OnDocumentClosing(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.OnDocumentTextChanged(Microsoft.CodeAnalysis.Document document) -> void
virtual Microsoft.CodeAnalysis.Workspace.OnProjectReloaded(Microsoft.CodeAnalysis.ProjectInfo reloadedProjectInfo) -> void
virtual Microsoft.CodeAnalysis.Workspace.OnProjectRemoved(Microsoft.CodeAnalysis.ProjectId projectId) -> void
virtual Microsoft.CodeAnalysis.Workspace.OnWorkspaceFailed(Microsoft.CodeAnalysis.WorkspaceDiagnostic diagnostic) -> void
virtual Microsoft.CodeAnalysis.Workspace.OpenAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
virtual Microsoft.CodeAnalysis.Workspace.OpenAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
virtual Microsoft.CodeAnalysis.Workspace.OpenDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
virtual Microsoft.CodeAnalysis.Workspace.PartialSemanticsEnabled.get -> bool
virtual Microsoft.CodeAnalysis.Workspace.TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution) -> bool
| abstract Microsoft.CodeAnalysis.CodeActions.CodeAction.Title.get -> string
abstract Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.ComputeOperationsAsync(object options, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
abstract Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.GetOptions(System.Threading.CancellationToken cancellationToken) -> object
abstract Microsoft.CodeAnalysis.CodeActions.PreviewOperation.GetPreviewAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<object>
abstract Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider.FixableDiagnosticIds.get -> System.Collections.Immutable.ImmutableArray<string>
abstract Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider.RegisterCodeFixesAsync(Microsoft.CodeAnalysis.CodeFixes.CodeFixContext context) -> System.Threading.Tasks.Task
abstract Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider.GetAllDiagnosticsAsync(Microsoft.CodeAnalysis.Project project, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>
abstract Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider.GetDocumentDiagnosticsAsync(Microsoft.CodeAnalysis.Document document, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>
abstract Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider.GetProjectDiagnosticsAsync(Microsoft.CodeAnalysis.Project project, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>
abstract Microsoft.CodeAnalysis.CodeFixes.FixAllProvider.GetFixAsync(Microsoft.CodeAnalysis.CodeFixes.FixAllContext fixAllContext) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.CodeActions.CodeAction>
abstract Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider.ComputeRefactoringsAsync(Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext context) -> System.Threading.Tasks.Task
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetChildren(TNode node) -> System.Collections.Generic.IEnumerable<TNode>
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetDescendants(TNode node) -> System.Collections.Generic.IEnumerable<TNode>
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetDistance(TNode oldNode, TNode newNode) -> double
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetLabel(TNode node) -> int
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.GetSpan(TNode node) -> Microsoft.CodeAnalysis.Text.TextSpan
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.LabelCount.get -> int
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.TiedToAncestor(int label) -> int
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.TreesEqual(TNode oldNode, TNode newNode) -> bool
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.TryGetParent(TNode node, out TNode parent) -> bool
abstract Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.ValuesEqual(TNode oldNode, TNode newNode) -> bool
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddBaseType(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode baseType) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddEventHandler(Microsoft.CodeAnalysis.SyntaxNode event, Microsoft.CodeAnalysis.SyntaxNode handler) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddInterfaceType(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AliasImportDeclaration(string aliasIdentifierName, Microsoft.CodeAnalysis.SyntaxNode name) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Argument(string name, Microsoft.CodeAnalysis.RefKind refKind, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ArrayCreationExpression(Microsoft.CodeAnalysis.SyntaxNode elementType, Microsoft.CodeAnalysis.SyntaxNode size) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ArrayCreationExpression(Microsoft.CodeAnalysis.SyntaxNode elementType, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> elements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ArrayTypeExpression(Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AsPrivateInterfaceImplementation(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType, string interfaceMemberName) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AsPublicInterfaceImplementation(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType, string interfaceMemberName) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AssignmentStatement(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Attribute(Microsoft.CodeAnalysis.SyntaxNode name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributeArguments = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AttributeArgument(string name, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AwaitExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.BaseExpression() -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.BitwiseAndExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.BitwiseNotExpression(Microsoft.CodeAnalysis.SyntaxNode operand) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.BitwiseOrExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CastExpression(Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CatchClause(Microsoft.CodeAnalysis.SyntaxNode type, string identifier, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ClassDeclaration(string name, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), Microsoft.CodeAnalysis.SyntaxNode baseType = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> interfaceTypes = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ClearTrivia<TNode>(TNode node) -> TNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CoalesceExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CompilationUnit(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> declarations) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConditionalAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode whenNotNull) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConditionalExpression(Microsoft.CodeAnalysis.SyntaxNode condition, Microsoft.CodeAnalysis.SyntaxNode whenTrue, Microsoft.CodeAnalysis.SyntaxNode whenFalse) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConstructorDeclaration(string containingTypeName = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> baseConstructorArguments = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConvertExpression(Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CustomEventDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> addAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> removeAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DefaultExpression(Microsoft.CodeAnalysis.ITypeSymbol type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DefaultExpression(Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DefaultSwitchSection(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DelegateDeclaration(string name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.SyntaxNode returnType = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers)) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DivideExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementBindingExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.EnumDeclaration(string name, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.EnumMember(string name, Microsoft.CodeAnalysis.SyntaxNode expression = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.EventDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers)) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ExitSwitchStatement() -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ExpressionStatement(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.FieldDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), Microsoft.CodeAnalysis.SyntaxNode initializer = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GenericName(string identifier, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAccessibility(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.Accessibility
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAccessorDeclaration(Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAccessors(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAttributeArguments(Microsoft.CodeAnalysis.SyntaxNode attributeDeclaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetBaseAndInterfaceTypes(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetDeclarationKind(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.Editing.DeclarationKind
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetExpression(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGetAccessorStatements(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetMembers(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetModifiers(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetName(Microsoft.CodeAnalysis.SyntaxNode declaration) -> string
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetParameters(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetSetAccessorStatements(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetStatements(Microsoft.CodeAnalysis.SyntaxNode declaration) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetSwitchSections(Microsoft.CodeAnalysis.SyntaxNode switchStatement) -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetType(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GreaterThanExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GreaterThanOrEqualExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IdentifierName(string identifier) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IfStatement(Microsoft.CodeAnalysis.SyntaxNode condition, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> trueStatements, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> falseStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IndexerDeclaration(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> getAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> setAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertAccessors(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> accessors) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertAttributeArguments(Microsoft.CodeAnalysis.SyntaxNode attributeDeclaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributes) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertMembers(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> imports) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertParameters(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributes) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertSwitchSections(Microsoft.CodeAnalysis.SyntaxNode switchStatement, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> switchSections) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InterfaceDeclaration(string name, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> interfaceTypes = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InvocationExpression(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IsTypeExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LambdaParameter(string identifier, Microsoft.CodeAnalysis.SyntaxNode type = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LessThanExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LessThanOrEqualExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LiteralExpression(object value) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LocalDeclarationStatement(Microsoft.CodeAnalysis.SyntaxNode type, string identifier, Microsoft.CodeAnalysis.SyntaxNode initializer = null, bool isConst = false) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LockStatement(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LogicalAndExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LogicalNotExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LogicalOrExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MemberBindingExpression(Microsoft.CodeAnalysis.SyntaxNode name) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MethodDeclaration(string name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.SyntaxNode returnType = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ModuloExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MultiplyExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NameExpression(Microsoft.CodeAnalysis.INamespaceOrTypeSymbol namespaceOrTypeSymbol) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NameOfExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceDeclaration(Microsoft.CodeAnalysis.SyntaxNode name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> declarations) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceImportDeclaration(Microsoft.CodeAnalysis.SyntaxNode name) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NegateExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NullableTypeExpression(Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ObjectCreationExpression(Microsoft.CodeAnalysis.SyntaxNode namedType, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ParameterDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type = null, Microsoft.CodeAnalysis.SyntaxNode initializer = null, Microsoft.CodeAnalysis.RefKind refKind = Microsoft.CodeAnalysis.RefKind.None) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.PropertyDeclaration(string name, Microsoft.CodeAnalysis.SyntaxNode type, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> getAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> setAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.QualifiedName(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReferenceEqualsExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReferenceNotEqualsExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveEventHandler(Microsoft.CodeAnalysis.SyntaxNode event, Microsoft.CodeAnalysis.SyntaxNode handler) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReturnStatement(Microsoft.CodeAnalysis.SyntaxNode expression = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SetAccessorDeclaration(Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.StructDeclaration(string name, System.Collections.Generic.IEnumerable<string> typeParameters = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> interfaceTypes = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SubtractExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SwitchSection(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> caseExpressions, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SwitchStatement(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> sections) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ThisExpression() -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ThrowExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ThrowStatement(Microsoft.CodeAnalysis.SyntaxNode expression = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryCastExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryCatchStatement(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> tryStatements, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> catchClauses, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> finallyStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleElementExpression(Microsoft.CodeAnalysis.SyntaxNode type, string name = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypedConstantExpression(Microsoft.CodeAnalysis.TypedConstant value) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypeExpression(Microsoft.CodeAnalysis.ITypeSymbol typeSymbol) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypeExpression(Microsoft.CodeAnalysis.SpecialType specialType) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypeOfExpression(Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.UsingStatement(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.UsingStatement(Microsoft.CodeAnalysis.SyntaxNode type, string name, Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueEqualsExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueNotEqualsExpression(Microsoft.CodeAnalysis.SyntaxNode left, Microsoft.CodeAnalysis.SyntaxNode right) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> lambdaParameters, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> lambdaParameters, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> lambdaParameters, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> lambdaParameters, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WhileStatement(Microsoft.CodeAnalysis.SyntaxNode condition, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithAccessibility(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Accessibility accessibility) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithAccessorDeclarations(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> accessorDeclarations) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithExpression(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithGetAccessorStatements(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithModifiers(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithName(Microsoft.CodeAnalysis.SyntaxNode declaration, string name) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithSetAccessorStatements(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithStatements(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithType(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode type) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeArguments(Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeConstraint(Microsoft.CodeAnalysis.SyntaxNode declaration, string typeParameterName, Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind kinds, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> types = null) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeParameters(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<string> typeParameters) -> Microsoft.CodeAnalysis.SyntaxNode
abstract Microsoft.CodeAnalysis.Host.HostLanguageServices.GetService<TLanguageService>() -> TLanguageService
abstract Microsoft.CodeAnalysis.Host.HostLanguageServices.Language.get -> string
abstract Microsoft.CodeAnalysis.Host.HostLanguageServices.WorkspaceServices.get -> Microsoft.CodeAnalysis.Host.HostWorkspaceServices
abstract Microsoft.CodeAnalysis.Host.HostServices.CreateWorkspaceServices(Microsoft.CodeAnalysis.Workspace workspace) -> Microsoft.CodeAnalysis.Host.HostWorkspaceServices
abstract Microsoft.CodeAnalysis.Host.HostWorkspaceServices.FindLanguageServices<TLanguageService>(Microsoft.CodeAnalysis.Host.HostWorkspaceServices.MetadataFilter filter) -> System.Collections.Generic.IEnumerable<TLanguageService>
abstract Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetService<TWorkspaceService>() -> TWorkspaceService
abstract Microsoft.CodeAnalysis.Host.HostWorkspaceServices.HostServices.get -> Microsoft.CodeAnalysis.Host.HostServices
abstract Microsoft.CodeAnalysis.Host.HostWorkspaceServices.Workspace.get -> Microsoft.CodeAnalysis.Workspace
abstract Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.OptionKey optionAndLanguage, object value) -> Microsoft.CodeAnalysis.Options.OptionSet
abstract Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction.GetDescription(System.Globalization.CultureInfo culture = null) -> string
abstract Microsoft.CodeAnalysis.TextLoader.LoadTextAndVersionAsync(Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.DocumentId documentId, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.TextAndVersion>
abstract Microsoft.CodeAnalysis.XmlDocumentationProvider.GetSourceStream(System.Threading.CancellationToken cancellationToken) -> System.IO.Stream
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ClassName = "class name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Comment = "comment" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ConstantName = "constant name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ControlKeyword = "keyword - control" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.DelegateName = "delegate name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.EnumMemberName = "enum member name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.EnumName = "enum name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.EventName = "event name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ExcludedCode = "excluded code" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ExtensionMethodName = "extension method name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.FieldName = "field name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Identifier = "identifier" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.InterfaceName = "interface name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Keyword = "keyword" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.LabelName = "label name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.LocalName = "local name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.MethodName = "method name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ModuleName = "module name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.NamespaceName = "namespace name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.NumericLiteral = "number" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Operator = "operator" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.OperatorOverloaded = "operator - overloaded" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.ParameterName = "parameter name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.PreprocessorKeyword = "preprocessor keyword" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.PreprocessorText = "preprocessor text" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.PropertyName = "property name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Punctuation = "punctuation" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexAlternation = "regex - alternation" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexAnchor = "regex - anchor" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexCharacterClass = "regex - character class" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexComment = "regex - comment" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexGrouping = "regex - grouping" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexOtherEscape = "regex - other escape" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexQuantifier = "regex - quantifier" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexSelfEscapedCharacter = "regex - self escaped character" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.RegexText = "regex - text" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.StaticSymbol = "static symbol" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.StringEscapeCharacter = "string - escape character" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.StringLiteral = "string" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.StructName = "struct name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.Text = "text" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.TypeParameterName = "type parameter name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.VerbatimStringLiteral = "string - verbatim" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.WhiteSpace = "whitespace" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentAttributeName = "xml doc comment - attribute name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentAttributeQuotes = "xml doc comment - attribute quotes" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentAttributeValue = "xml doc comment - attribute value" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentCDataSection = "xml doc comment - cdata section" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentComment = "xml doc comment - comment" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentDelimiter = "xml doc comment - delimiter" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentEntityReference = "xml doc comment - entity reference" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentName = "xml doc comment - name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentProcessingInstruction = "xml doc comment - processing instruction" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlDocCommentText = "xml doc comment - text" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralAttributeName = "xml literal - attribute name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralAttributeQuotes = "xml literal - attribute quotes" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralAttributeValue = "xml literal - attribute value" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralCDataSection = "xml literal - cdata section" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralComment = "xml literal - comment" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralDelimiter = "xml literal - delimiter" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralEmbeddedExpression = "xml literal - embedded expression" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralEntityReference = "xml literal - entity reference" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralName = "xml literal - name" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralProcessingInstruction = "xml literal - processing instruction" -> string
const Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.XmlLiteralText = "xml literal - text" -> string
const Microsoft.CodeAnalysis.CodeActions.ConflictAnnotation.Kind = "CodeAction_Conflict" -> string
const Microsoft.CodeAnalysis.CodeActions.RenameAnnotation.Kind = "CodeAction_Rename" -> string
const Microsoft.CodeAnalysis.CodeActions.WarningAnnotation.Kind = "CodeAction_Warning" -> string
const Microsoft.CodeAnalysis.Host.Mef.ServiceLayer.Default = "Default" -> string
const Microsoft.CodeAnalysis.Host.Mef.ServiceLayer.Desktop = "Desktop" -> string
const Microsoft.CodeAnalysis.Host.Mef.ServiceLayer.Editor = "Editor" -> string
const Microsoft.CodeAnalysis.Host.Mef.ServiceLayer.Host = "Host" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Assembly = "Assembly" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Class = "Class" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Constant = "Constant" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Delegate = "Delegate" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Enum = "Enum" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.EnumMember = "EnumMember" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Error = "Error" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Event = "Event" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.ExtensionMethod = "ExtensionMethod" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Field = "Field" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.File = "File" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Folder = "Folder" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Interface = "Interface" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Internal = "Internal" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Intrinsic = "Intrinsic" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Keyword = "Keyword" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Label = "Label" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Local = "Local" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Method = "Method" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Module = "Module" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Namespace = "Namespace" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Operator = "Operator" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Parameter = "Parameter" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Private = "Private" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Project = "Project" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Property = "Property" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Protected = "Protected" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Public = "Public" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.RangeVariable = "RangeVariable" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Reference = "Reference" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Snippet = "Snippet" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Structure = "Structure" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.TypeParameter = "TypeParameter" -> string
const Microsoft.CodeAnalysis.Tags.WellKnownTags.Warning = "Warning" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.Debugger = "Debugger" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.Host = "Host" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.Interactive = "Interactive" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.MetadataAsSource = "MetadataAsSource" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.MiscellaneousFiles = "MiscellaneousFiles" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.MSBuild = "MSBuildWorkspace" -> string
const Microsoft.CodeAnalysis.WorkspaceKind.Preview = "Preview" -> string
Microsoft.CodeAnalysis.AdditionalDocument
Microsoft.CodeAnalysis.AdhocWorkspace
Microsoft.CodeAnalysis.AdhocWorkspace.AddDocument(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.AdhocWorkspace.AddDocument(Microsoft.CodeAnalysis.ProjectId projectId, string name, Microsoft.CodeAnalysis.Text.SourceText text) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.AdhocWorkspace.AddProject(Microsoft.CodeAnalysis.ProjectInfo projectInfo) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.AdhocWorkspace.AddProject(string name, string language) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.AdhocWorkspace.AddProjects(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectInfo> projectInfos) -> void
Microsoft.CodeAnalysis.AdhocWorkspace.AddSolution(Microsoft.CodeAnalysis.SolutionInfo solutionInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.AdhocWorkspace.AdhocWorkspace() -> void
Microsoft.CodeAnalysis.AdhocWorkspace.AdhocWorkspace(Microsoft.CodeAnalysis.Host.HostServices host, string workspaceKind = "Custom") -> void
Microsoft.CodeAnalysis.AdhocWorkspace.ClearSolution() -> void
Microsoft.CodeAnalysis.AnalyzerConfigDocument
Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddAdditionalDocument = 11 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddAnalyzerConfigDocument = 17 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddAnalyzerReference = 9 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddDocument = 6 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddMetadataReference = 4 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddProject = 0 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddProjectReference = 2 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.AddSolutionAnalyzerReference = 20 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeAdditionalDocument = 13 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeAnalyzerConfigDocument = 19 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeCompilationOptions = 14 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeDocument = 8 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeDocumentInfo = 16 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.ChangeParseOptions = 15 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveAdditionalDocument = 12 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveAnalyzerConfigDocument = 18 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveAnalyzerReference = 10 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveDocument = 7 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveMetadataReference = 5 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveProject = 1 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveProjectReference = 3 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.ApplyChangesKind.RemoveSolutionAnalyzerReference = 21 -> Microsoft.CodeAnalysis.ApplyChangesKind
Microsoft.CodeAnalysis.Classification.ClassificationTypeNames
Microsoft.CodeAnalysis.Classification.ClassifiedSpan
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.ClassificationType.get -> string
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.ClassifiedSpan() -> void
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.ClassifiedSpan(Microsoft.CodeAnalysis.Text.TextSpan textSpan, string classificationType) -> void
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.ClassifiedSpan(string classificationType, Microsoft.CodeAnalysis.Text.TextSpan textSpan) -> void
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.Equals(Microsoft.CodeAnalysis.Classification.ClassifiedSpan other) -> bool
Microsoft.CodeAnalysis.Classification.ClassifiedSpan.TextSpan.get -> Microsoft.CodeAnalysis.Text.TextSpan
Microsoft.CodeAnalysis.Classification.Classifier
Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation
Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation.ApplyChangesOperation(Microsoft.CodeAnalysis.Solution changedSolution) -> void
Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation.ChangedSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.CodeActions.CodeAction
Microsoft.CodeAnalysis.CodeActions.CodeAction.CodeAction() -> void
Microsoft.CodeAnalysis.CodeActions.CodeAction.GetOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessAsync(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation> operations, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessChangesAsync(Microsoft.CodeAnalysis.Solution changedSolution, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
Microsoft.CodeAnalysis.CodeActions.CodeActionOperation
Microsoft.CodeAnalysis.CodeActions.CodeActionOperation.CodeActionOperation() -> void
Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions
Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.CodeActionWithOptions() -> void
Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.GetOperationsAsync(object options, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
Microsoft.CodeAnalysis.CodeActions.ConflictAnnotation
Microsoft.CodeAnalysis.CodeActions.OpenDocumentOperation
Microsoft.CodeAnalysis.CodeActions.OpenDocumentOperation.DocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.CodeActions.OpenDocumentOperation.OpenDocumentOperation(Microsoft.CodeAnalysis.DocumentId documentId, bool activateIfAlreadyOpen = false) -> void
Microsoft.CodeAnalysis.CodeActions.PreviewOperation
Microsoft.CodeAnalysis.CodeActions.PreviewOperation.PreviewOperation() -> void
Microsoft.CodeAnalysis.CodeActions.RenameAnnotation
Microsoft.CodeAnalysis.CodeActions.WarningAnnotation
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.CodeFixContext() -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.CodeFixContext(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Diagnostic diagnostic, System.Action<Microsoft.CodeAnalysis.CodeActions.CodeAction, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>> registerCodeFix, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.CodeFixContext(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic> diagnostics, System.Action<Microsoft.CodeAnalysis.CodeActions.CodeAction, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>> registerCodeFix, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.Diagnostics.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.RegisterCodeFix(Microsoft.CodeAnalysis.CodeActions.CodeAction action, Microsoft.CodeAnalysis.Diagnostic diagnostic) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.RegisterCodeFix(Microsoft.CodeAnalysis.CodeActions.CodeAction action, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic> diagnostics) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.RegisterCodeFix(Microsoft.CodeAnalysis.CodeActions.CodeAction action, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic> diagnostics) -> void
Microsoft.CodeAnalysis.CodeFixes.CodeFixContext.Span.get -> Microsoft.CodeAnalysis.Text.TextSpan
Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider
Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider.CodeFixProvider() -> void
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute.ExportCodeFixProviderAttribute(string firstLanguage, params string[] additionalLanguages) -> void
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute.Languages.get -> string[]
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute.Name.get -> string
Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute.Name.set -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllContext
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.CodeActionEquivalenceKey.get -> string
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.CodeFixProvider.get -> Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticIds.get -> System.Collections.Immutable.ImmutableHashSet<string>
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider.DiagnosticProvider() -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.FixAllContext(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider codeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllScope scope, string codeActionEquivalenceKey, System.Collections.Generic.IEnumerable<string> diagnosticIds, Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider fixAllDiagnosticProvider, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.FixAllContext(Microsoft.CodeAnalysis.Project project, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider codeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllScope scope, string codeActionEquivalenceKey, System.Collections.Generic.IEnumerable<string> diagnosticIds, Microsoft.CodeAnalysis.CodeFixes.FixAllContext.DiagnosticProvider fixAllDiagnosticProvider, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.GetAllDiagnosticsAsync(Microsoft.CodeAnalysis.Project project) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>>
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.GetDocumentDiagnosticsAsync(Microsoft.CodeAnalysis.Document document) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>>
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.GetProjectDiagnosticsAsync(Microsoft.CodeAnalysis.Project project) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Diagnostic>>
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.Project.get -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.Scope.get -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.Solution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.CodeFixes.FixAllContext.WithCancellationToken(System.Threading.CancellationToken cancellationToken) -> Microsoft.CodeAnalysis.CodeFixes.FixAllContext
Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
Microsoft.CodeAnalysis.CodeFixes.FixAllProvider.FixAllProvider() -> void
Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllScope.Custom = 3 -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllScope.Document = 0 -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllScope.Project = 1 -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.FixAllScope.Solution = 2 -> Microsoft.CodeAnalysis.CodeFixes.FixAllScope
Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.CodeRefactoringContext() -> void
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.CodeRefactoringContext(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, System.Action<Microsoft.CodeAnalysis.CodeActions.CodeAction> registerRefactoring, System.Threading.CancellationToken cancellationToken) -> void
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.RegisterRefactoring(Microsoft.CodeAnalysis.CodeActions.CodeAction action) -> void
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringContext.Span.get -> Microsoft.CodeAnalysis.Text.TextSpan
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider
Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider.CodeRefactoringProvider() -> void
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute.ExportCodeRefactoringProviderAttribute(string firstLanguage, params string[] additionalLanguages) -> void
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute.Languages.get -> string[]
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute.Name.get -> string
Microsoft.CodeAnalysis.CodeRefactorings.ExportCodeRefactoringProviderAttribute.Name.set -> void
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.CodeStyleOption(T value, Microsoft.CodeAnalysis.CodeStyle.NotificationOption notification) -> void
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Equals(Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T> other) -> bool
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Notification.get -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Notification.set -> void
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.ToXElement() -> System.Xml.Linq.XElement
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Value.get -> T
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Value.set -> void
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions
Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.CodeStyleOptions() -> void
Microsoft.CodeAnalysis.CodeStyle.NotificationOption
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Name.get -> string
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Name.set -> void
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Severity.get -> Microsoft.CodeAnalysis.ReportDiagnostic
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Severity.set -> void
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Value.get -> Microsoft.CodeAnalysis.DiagnosticSeverity
Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Value.set -> void
Microsoft.CodeAnalysis.CompilationOutputInfo
Microsoft.CodeAnalysis.CompilationOutputInfo.AssemblyPath.get -> string
Microsoft.CodeAnalysis.CompilationOutputInfo.CompilationOutputInfo() -> void
Microsoft.CodeAnalysis.CompilationOutputInfo.Equals(Microsoft.CodeAnalysis.CompilationOutputInfo other) -> bool
Microsoft.CodeAnalysis.CompilationOutputInfo.WithAssemblyPath(string path) -> Microsoft.CodeAnalysis.CompilationOutputInfo
Microsoft.CodeAnalysis.Differencing.Edit<TNode>
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.Edit() -> void
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.Equals(Microsoft.CodeAnalysis.Differencing.Edit<TNode> other) -> bool
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.Kind.get -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.NewNode.get -> TNode
Microsoft.CodeAnalysis.Differencing.Edit<TNode>.OldNode.get -> TNode
Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Delete = 3 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Insert = 2 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Move = 4 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.None = 0 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Reorder = 5 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditKind.Update = 1 -> Microsoft.CodeAnalysis.Differencing.EditKind
Microsoft.CodeAnalysis.Differencing.EditScript<TNode>
Microsoft.CodeAnalysis.Differencing.EditScript<TNode>.Edits.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Differencing.Edit<TNode>>
Microsoft.CodeAnalysis.Differencing.EditScript<TNode>.Match.get -> Microsoft.CodeAnalysis.Differencing.Match<TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.Comparer.get -> Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.GetSequenceEdits(System.Collections.Generic.IEnumerable<TNode> oldNodes, System.Collections.Generic.IEnumerable<TNode> newNodes) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Differencing.Edit<TNode>>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.GetTreeEdits() -> Microsoft.CodeAnalysis.Differencing.EditScript<TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.Matches.get -> System.Collections.Generic.IReadOnlyDictionary<TNode, TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.NewRoot.get -> TNode
Microsoft.CodeAnalysis.Differencing.Match<TNode>.OldRoot.get -> TNode
Microsoft.CodeAnalysis.Differencing.Match<TNode>.ReverseMatches.get -> System.Collections.Generic.IReadOnlyDictionary<TNode, TNode>
Microsoft.CodeAnalysis.Differencing.Match<TNode>.TryGetNewNode(TNode oldNode, out TNode newNode) -> bool
Microsoft.CodeAnalysis.Differencing.Match<TNode>.TryGetOldNode(TNode newNode, out TNode oldNode) -> bool
Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>
Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.ComputeEditScript(TNode oldRoot, TNode newRoot) -> Microsoft.CodeAnalysis.Differencing.EditScript<TNode>
Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.ComputeMatch(TNode oldRoot, TNode newRoot, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TNode, TNode>> knownMatches = null) -> Microsoft.CodeAnalysis.Differencing.Match<TNode>
Microsoft.CodeAnalysis.Differencing.TreeComparer<TNode>.TreeComparer() -> void
Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.GetLinkedDocumentIds() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.Document.GetOptionsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Options.DocumentOptionSet>
Microsoft.CodeAnalysis.Document.GetSemanticModelAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SemanticModel>
Microsoft.CodeAnalysis.Document.GetSyntaxRootAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxNode>
Microsoft.CodeAnalysis.Document.GetSyntaxTreeAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxTree>
Microsoft.CodeAnalysis.Document.GetSyntaxVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Document.GetTextChangesAsync(Microsoft.CodeAnalysis.Document oldDocument, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextChange>>
Microsoft.CodeAnalysis.Document.SourceCodeKind.get -> Microsoft.CodeAnalysis.SourceCodeKind
Microsoft.CodeAnalysis.Document.SupportsSemanticModel.get -> bool
Microsoft.CodeAnalysis.Document.SupportsSyntaxTree.get -> bool
Microsoft.CodeAnalysis.Document.TryGetSemanticModel(out Microsoft.CodeAnalysis.SemanticModel semanticModel) -> bool
Microsoft.CodeAnalysis.Document.TryGetSyntaxRoot(out Microsoft.CodeAnalysis.SyntaxNode root) -> bool
Microsoft.CodeAnalysis.Document.TryGetSyntaxTree(out Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> bool
Microsoft.CodeAnalysis.Document.TryGetSyntaxVersion(out Microsoft.CodeAnalysis.VersionStamp version) -> bool
Microsoft.CodeAnalysis.Document.WithFilePath(string filePath) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithFolders(System.Collections.Generic.IEnumerable<string> folders) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithName(string name) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithSourceCodeKind(Microsoft.CodeAnalysis.SourceCodeKind kind) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithSyntaxRoot(Microsoft.CodeAnalysis.SyntaxNode root) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Document.WithText(Microsoft.CodeAnalysis.Text.SourceText text) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.DocumentActiveContextChangedEventArgs(Microsoft.CodeAnalysis.Solution solution, Microsoft.CodeAnalysis.Text.SourceTextContainer sourceTextContainer, Microsoft.CodeAnalysis.DocumentId oldActiveContextDocumentId, Microsoft.CodeAnalysis.DocumentId newActiveContextDocumentId) -> void
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.NewActiveContextDocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.OldActiveContextDocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.Solution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs.SourceTextContainer.get -> Microsoft.CodeAnalysis.Text.SourceTextContainer
Microsoft.CodeAnalysis.DocumentDiagnostic
Microsoft.CodeAnalysis.DocumentDiagnostic.DocumentDiagnostic(Microsoft.CodeAnalysis.WorkspaceDiagnosticKind kind, string message, Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.DocumentDiagnostic.DocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentEventArgs
Microsoft.CodeAnalysis.DocumentEventArgs.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.DocumentEventArgs.DocumentEventArgs(Microsoft.CodeAnalysis.Document document) -> void
Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentId.Equals(Microsoft.CodeAnalysis.DocumentId other) -> bool
Microsoft.CodeAnalysis.DocumentId.Id.get -> System.Guid
Microsoft.CodeAnalysis.DocumentId.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.FilePath.get -> string
Microsoft.CodeAnalysis.DocumentInfo.Folders.get -> System.Collections.Generic.IReadOnlyList<string>
Microsoft.CodeAnalysis.DocumentInfo.Id.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.DocumentInfo.IsGenerated.get -> bool
Microsoft.CodeAnalysis.DocumentInfo.Name.get -> string
Microsoft.CodeAnalysis.DocumentInfo.SourceCodeKind.get -> Microsoft.CodeAnalysis.SourceCodeKind
Microsoft.CodeAnalysis.DocumentInfo.TextLoader.get -> Microsoft.CodeAnalysis.TextLoader
Microsoft.CodeAnalysis.DocumentInfo.WithFilePath(string filePath) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithFolders(System.Collections.Generic.IEnumerable<string> folders) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithId(Microsoft.CodeAnalysis.DocumentId id) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithName(string name) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithSourceCodeKind(Microsoft.CodeAnalysis.SourceCodeKind kind) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.DocumentInfo.WithTextLoader(Microsoft.CodeAnalysis.TextLoader loader) -> Microsoft.CodeAnalysis.DocumentInfo
Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.AddAccessor = 26 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Attribute = 22 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Class = 2 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.CompilationUnit = 1 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Constructor = 10 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.ConversionOperator = 9 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.CustomEvent = 17 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Delegate = 6 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Destructor = 11 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Enum = 5 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.EnumMember = 15 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Event = 16 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Field = 12 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.GetAccessor = 24 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Indexer = 14 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Interface = 4 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.LambdaExpression = 23 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Method = 7 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Namespace = 18 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.NamespaceImport = 19 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.None = 0 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Operator = 8 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Parameter = 20 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Property = 13 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.RaiseAccessor = 28 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.RemoveAccessor = 27 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.SetAccessor = 25 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Struct = 3 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationKind.Variable = 21 -> Microsoft.CodeAnalysis.Editing.DeclarationKind
Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.DeclarationModifiers() -> void
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Equals(Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsAbstract.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsAsync.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsConst.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsExtern.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsNew.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsOverride.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsPartial.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsReadOnly.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsRef.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsSealed.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsStatic.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsUnsafe.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsVirtual.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsVolatile.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsWithEvents.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.IsWriteOnly.get -> bool
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithAsync(bool isAsync) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsAbstract(bool isAbstract) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsConst(bool isConst) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsExtern(bool isExtern) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsNew(bool isNew) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsOverride(bool isOverride) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsReadOnly(bool isReadOnly) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsRef(bool isRef) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsSealed(bool isSealed) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsStatic(bool isStatic) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsUnsafe(bool isUnsafe) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsVirtual(bool isVirtual) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsVolatile(bool isVolatile) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithIsWriteOnly(bool isWriteOnly) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithPartial(bool isPartial) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithWithEvents(bool withEvents) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
Microsoft.CodeAnalysis.Editing.DocumentEditor
Microsoft.CodeAnalysis.Editing.DocumentEditor.GetChangedDocument() -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Editing.DocumentEditor.OriginalDocument.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Editing.DocumentEditor.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel
Microsoft.CodeAnalysis.Editing.ImportAdder
Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Addition = 2 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.BitwiseAnd = 3 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.BitwiseOr = 4 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Decrement = 5 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Division = 6 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Equality = 7 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.ExclusiveOr = 8 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.ExplicitConversion = 1 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.False = 9 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.GreaterThan = 10 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.GreaterThanOrEqual = 11 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.ImplicitConversion = 0 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Increment = 12 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Inequality = 13 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.LeftShift = 14 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.LessThan = 15 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.LessThanOrEqual = 16 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.LogicalNot = 17 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Modulus = 18 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Multiply = 19 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.OnesComplement = 20 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.RightShift = 21 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.Subtraction = 22 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.True = 23 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.UnaryNegation = 24 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.OperatorKind.UnaryPlus = 25 -> Microsoft.CodeAnalysis.Editing.OperatorKind
Microsoft.CodeAnalysis.Editing.SolutionEditor
Microsoft.CodeAnalysis.Editing.SolutionEditor.GetChangedSolution() -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Editing.SolutionEditor.GetDocumentEditorAsync(Microsoft.CodeAnalysis.DocumentId id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Editing.DocumentEditor>
Microsoft.CodeAnalysis.Editing.SolutionEditor.OriginalSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Editing.SolutionEditor.SolutionEditor(Microsoft.CodeAnalysis.Solution solution) -> void
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind.Constructor = 4 -> Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind.None = 0 -> Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind.ReferenceType = 1 -> Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind.ValueType = 2 -> Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind
Microsoft.CodeAnalysis.Editing.SymbolEditor
Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction
Microsoft.CodeAnalysis.Editing.SymbolEditor.ChangedSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditAllDeclarationsAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditAllDeclarationsAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.ISymbol member, Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.ISymbol member, Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Location location, Microsoft.CodeAnalysis.Editing.SymbolEditor.AsyncDeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.EditOneDeclarationAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Location location, Microsoft.CodeAnalysis.Editing.SymbolEditor.DeclarationEditAction editAction, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.GetChangedDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Document>
Microsoft.CodeAnalysis.Editing.SymbolEditor.GetCurrentDeclarationsAsync(Microsoft.CodeAnalysis.ISymbol symbol, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.SyntaxNode>>
Microsoft.CodeAnalysis.Editing.SymbolEditor.GetCurrentSymbolAsync(Microsoft.CodeAnalysis.ISymbol symbol, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
Microsoft.CodeAnalysis.Editing.SymbolEditor.OriginalSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Editing.SymbolEditorExtensions
Microsoft.CodeAnalysis.Editing.SyntaxEditor
Microsoft.CodeAnalysis.Editing.SyntaxEditor.Generator.get -> Microsoft.CodeAnalysis.Editing.SyntaxGenerator
Microsoft.CodeAnalysis.Editing.SyntaxEditor.GetChangedRoot() -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxEditor.InsertAfter(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxNode newNode) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.InsertAfter(Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> newNodes) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.InsertBefore(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxNode newNode) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.InsertBefore(Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> newNodes) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.OriginalRoot.get -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxEditor.RemoveNode(Microsoft.CodeAnalysis.SyntaxNode node) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.RemoveNode(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxRemoveOptions options) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.ReplaceNode(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxNode newNode) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.ReplaceNode(Microsoft.CodeAnalysis.SyntaxNode node, System.Func<Microsoft.CodeAnalysis.SyntaxNode, Microsoft.CodeAnalysis.Editing.SyntaxGenerator, Microsoft.CodeAnalysis.SyntaxNode> computeReplacement) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.SyntaxEditor(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.Workspace workspace) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditor.TrackNode(Microsoft.CodeAnalysis.SyntaxNode node) -> void
Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions
Microsoft.CodeAnalysis.Editing.SyntaxGenerator
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddAccessors(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> accessors) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddAttributeArguments(Microsoft.CodeAnalysis.SyntaxNode attributeDeclaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddMembers(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] members) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddMembers(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] imports) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> imports) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddParameters(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AddSwitchSections(Microsoft.CodeAnalysis.SyntaxNode switchStatement, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> switchSections) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AliasImportDeclaration(string aliasIdentifierName, Microsoft.CodeAnalysis.INamespaceOrTypeSymbol symbol) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Argument(Microsoft.CodeAnalysis.RefKind refKind, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Argument(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AsPrivateInterfaceImplementation(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AsPublicInterfaceImplementation(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Attribute(Microsoft.CodeAnalysis.AttributeData attribute) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Attribute(string name, params Microsoft.CodeAnalysis.SyntaxNode[] attributeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Attribute(string name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> attributeArguments = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.AttributeArgument(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CastExpression(Microsoft.CodeAnalysis.ITypeSymbol type, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CatchClause(Microsoft.CodeAnalysis.ITypeSymbol type, string identifier, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CompilationUnit(params Microsoft.CodeAnalysis.SyntaxNode[] declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConstructorDeclaration(Microsoft.CodeAnalysis.IMethodSymbol constructorMethod, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> baseConstructorArguments = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ConvertExpression(Microsoft.CodeAnalysis.ITypeSymbol type, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.CustomEventDeclaration(Microsoft.CodeAnalysis.IEventSymbol symbol, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> addAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> removeAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.Declaration(Microsoft.CodeAnalysis.ISymbol symbol) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DottedName(string dottedName) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ElementBindingExpression(params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.EventDeclaration(Microsoft.CodeAnalysis.IEventSymbol symbol) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.FalseLiteralExpression() -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.FieldDeclaration(Microsoft.CodeAnalysis.IFieldSymbol field) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.FieldDeclaration(Microsoft.CodeAnalysis.IFieldSymbol field, Microsoft.CodeAnalysis.SyntaxNode initializer) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GenericName(string identifier, params Microsoft.CodeAnalysis.ITypeSymbol[] typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GenericName(string identifier, params Microsoft.CodeAnalysis.SyntaxNode[] typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GenericName(string identifier, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ITypeSymbol> typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetAccessor(Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Editing.DeclarationKind kind) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetDeclaration(Microsoft.CodeAnalysis.SyntaxNode node) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetDeclaration(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Editing.DeclarationKind kind) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IfStatement(Microsoft.CodeAnalysis.SyntaxNode condition, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> trueStatements, Microsoft.CodeAnalysis.SyntaxNode falseStatement) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IndexerDeclaration(Microsoft.CodeAnalysis.IPropertySymbol indexer, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> getAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> setAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IndexOf<T>(System.Collections.Generic.IReadOnlyList<T> list, T element) -> int
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, params Microsoft.CodeAnalysis.SyntaxNode[] attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertMembers(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, params Microsoft.CodeAnalysis.SyntaxNode[] members) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertNamespaceImports(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, params Microsoft.CodeAnalysis.SyntaxNode[] imports) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertReturnAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration, int index, params Microsoft.CodeAnalysis.SyntaxNode[] attributes) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InvocationExpression(Microsoft.CodeAnalysis.SyntaxNode expression, params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.IsTypeExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.ITypeSymbol type) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LambdaParameter(string identifier, Microsoft.CodeAnalysis.ITypeSymbol type) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LocalDeclarationStatement(Microsoft.CodeAnalysis.ITypeSymbol type, string name, Microsoft.CodeAnalysis.SyntaxNode initializer = null, bool isConst = false) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.LocalDeclarationStatement(string name, Microsoft.CodeAnalysis.SyntaxNode initializer) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MemberAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, string memberName) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MethodDeclaration(Microsoft.CodeAnalysis.IMethodSymbol method, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceDeclaration(Microsoft.CodeAnalysis.SyntaxNode name, params Microsoft.CodeAnalysis.SyntaxNode[] declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceDeclaration(string name, params Microsoft.CodeAnalysis.SyntaxNode[] declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceDeclaration(string name, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NamespaceImportDeclaration(string name) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.NullLiteralExpression() -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ObjectCreationExpression(Microsoft.CodeAnalysis.ITypeSymbol type, params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ObjectCreationExpression(Microsoft.CodeAnalysis.ITypeSymbol type, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ObjectCreationExpression(Microsoft.CodeAnalysis.SyntaxNode type, params Microsoft.CodeAnalysis.SyntaxNode[] arguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.OperatorDeclaration(Microsoft.CodeAnalysis.IMethodSymbol method, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ParameterDeclaration(Microsoft.CodeAnalysis.IParameterSymbol symbol, Microsoft.CodeAnalysis.SyntaxNode initializer = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.PropertyDeclaration(Microsoft.CodeAnalysis.IPropertySymbol property, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> getAccessorStatements = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> setAccessorStatements = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveAllAttributes(Microsoft.CodeAnalysis.SyntaxNode declaration) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveNodes(Microsoft.CodeAnalysis.SyntaxNode root, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> declarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SwitchSection(Microsoft.CodeAnalysis.SyntaxNode caseExpression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SwitchStatement(Microsoft.CodeAnalysis.SyntaxNode expression, params Microsoft.CodeAnalysis.SyntaxNode[] sections) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.SyntaxGenerator() -> void
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TrueLiteralExpression() -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryCastExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.ITypeSymbol type) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryCatchStatement(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> tryStatements, params Microsoft.CodeAnalysis.SyntaxNode[] catchClauses) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TryFinallyStatement(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> tryStatements, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> finallyStatements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleElementExpression(Microsoft.CodeAnalysis.ITypeSymbol type, string name = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleTypeExpression(params Microsoft.CodeAnalysis.SyntaxNode[] elements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleTypeExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ITypeSymbol> elementTypes, System.Collections.Generic.IEnumerable<string> elementNames = null) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TupleTypeExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> elements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.TypeExpression(Microsoft.CodeAnalysis.ITypeSymbol typeSymbol, bool addImport) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.UsingStatement(string name, Microsoft.CodeAnalysis.SyntaxNode expression, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(string parameterName, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(string parameterName, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ValueReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(string parameterName, Microsoft.CodeAnalysis.SyntaxNode expression) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(string parameterName, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.VoidReturningLambdaExpression(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithAccessorDeclarations(Microsoft.CodeAnalysis.SyntaxNode declaration, params Microsoft.CodeAnalysis.SyntaxNode[] accessorDeclarations) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeArguments(Microsoft.CodeAnalysis.SyntaxNode expression, params Microsoft.CodeAnalysis.SyntaxNode[] typeArguments) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeConstraint(Microsoft.CodeAnalysis.SyntaxNode declaration, string typeParameterName, Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind kinds, params Microsoft.CodeAnalysis.SyntaxNode[] types) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeConstraint(Microsoft.CodeAnalysis.SyntaxNode declaration, string typeParameterName, params Microsoft.CodeAnalysis.SyntaxNode[] types) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.Editing.SyntaxGenerator.WithTypeParameters(Microsoft.CodeAnalysis.SyntaxNode declaration, params string[] typeParameters) -> Microsoft.CodeAnalysis.SyntaxNode
Microsoft.CodeAnalysis.ExtensionOrderAttribute
Microsoft.CodeAnalysis.ExtensionOrderAttribute.After.get -> string
Microsoft.CodeAnalysis.ExtensionOrderAttribute.After.set -> void
Microsoft.CodeAnalysis.ExtensionOrderAttribute.Before.get -> string
Microsoft.CodeAnalysis.ExtensionOrderAttribute.Before.set -> void
Microsoft.CodeAnalysis.ExtensionOrderAttribute.ExtensionOrderAttribute() -> void
Microsoft.CodeAnalysis.FileTextLoader
Microsoft.CodeAnalysis.FileTextLoader.DefaultEncoding.get -> System.Text.Encoding
Microsoft.CodeAnalysis.FileTextLoader.FileTextLoader(string path, System.Text.Encoding defaultEncoding) -> void
Microsoft.CodeAnalysis.FileTextLoader.Path.get -> string
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnCompleted() -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnDefinitionFound(Microsoft.CodeAnalysis.ISymbol symbol) -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnFindInDocumentCompleted(Microsoft.CodeAnalysis.Document document) -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnFindInDocumentStarted(Microsoft.CodeAnalysis.Document document) -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnReferenceFound(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation location) -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.OnStarted() -> void
Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress.ReportProgress(int current, int maximum) -> void
Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol
Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol.Definition.get -> Microsoft.CodeAnalysis.ISymbol
Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol.Locations.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation>
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Alias.get -> Microsoft.CodeAnalysis.IAliasSymbol
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.CandidateReason.get -> Microsoft.CodeAnalysis.CandidateReason
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.CompareTo(Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation other) -> int
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Document.get -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Equals(Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation other) -> bool
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.IsCandidateLocation.get -> bool
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.IsImplicit.get -> bool
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Location.get -> Microsoft.CodeAnalysis.Location
Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.ReferenceLocation() -> void
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.CalledSymbol.get -> Microsoft.CodeAnalysis.ISymbol
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.CallingSymbol.get -> Microsoft.CodeAnalysis.ISymbol
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.IsDirect.get -> bool
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.Locations.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Location>
Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo.SymbolCallerInfo() -> void
Microsoft.CodeAnalysis.FindSymbols.SymbolFinder
Microsoft.CodeAnalysis.Formatting.Formatter
Microsoft.CodeAnalysis.Formatting.FormattingOptions
Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle
Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Block = 1 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle
Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.None = 0 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle
Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle.Smart = 2 -> Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle
Microsoft.CodeAnalysis.Host.HostLanguageServices
Microsoft.CodeAnalysis.Host.HostLanguageServices.GetRequiredService<TLanguageService>() -> TLanguageService
Microsoft.CodeAnalysis.Host.HostLanguageServices.HostLanguageServices() -> void
Microsoft.CodeAnalysis.Host.HostServices
Microsoft.CodeAnalysis.Host.HostServices.HostServices() -> void
Microsoft.CodeAnalysis.Host.HostWorkspaceServices
Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetRequiredService<TWorkspaceService>() -> TWorkspaceService
Microsoft.CodeAnalysis.Host.HostWorkspaceServices.HostWorkspaceServices() -> void
Microsoft.CodeAnalysis.Host.HostWorkspaceServices.MetadataFilter
Microsoft.CodeAnalysis.Host.IAnalyzerService
Microsoft.CodeAnalysis.Host.IAnalyzerService.GetLoader() -> Microsoft.CodeAnalysis.IAnalyzerAssemblyLoader
Microsoft.CodeAnalysis.Host.ILanguageService
Microsoft.CodeAnalysis.Host.IPersistentStorage
Microsoft.CodeAnalysis.Host.IPersistentStorage.ReadStreamAsync(Microsoft.CodeAnalysis.Document document, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.IO.Stream>
Microsoft.CodeAnalysis.Host.IPersistentStorage.ReadStreamAsync(Microsoft.CodeAnalysis.Project project, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.IO.Stream>
Microsoft.CodeAnalysis.Host.IPersistentStorage.ReadStreamAsync(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.IO.Stream>
Microsoft.CodeAnalysis.Host.IPersistentStorage.WriteStreamAsync(Microsoft.CodeAnalysis.Document document, string name, System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<bool>
Microsoft.CodeAnalysis.Host.IPersistentStorage.WriteStreamAsync(Microsoft.CodeAnalysis.Project project, string name, System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<bool>
Microsoft.CodeAnalysis.Host.IPersistentStorage.WriteStreamAsync(string name, System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<bool>
Microsoft.CodeAnalysis.Host.IPersistentStorageService
Microsoft.CodeAnalysis.Host.IPersistentStorageService.GetStorage(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.Host.IPersistentStorage
Microsoft.CodeAnalysis.Host.ITemporaryStorageService
Microsoft.CodeAnalysis.Host.ITemporaryStorageService.CreateTemporaryStreamStorage(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage
Microsoft.CodeAnalysis.Host.ITemporaryStorageService.CreateTemporaryTextStorage(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Host.ITemporaryTextStorage
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage.ReadStream(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.IO.Stream
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage.ReadStreamAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.IO.Stream>
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage.WriteStream(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void
Microsoft.CodeAnalysis.Host.ITemporaryStreamStorage.WriteStreamAsync(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage.ReadText(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Text.SourceText
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage.ReadTextAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Text.SourceText>
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage.WriteText(Microsoft.CodeAnalysis.Text.SourceText text, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void
Microsoft.CodeAnalysis.Host.ITemporaryTextStorage.WriteTextAsync(Microsoft.CodeAnalysis.Text.SourceText text, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Host.IWorkspaceService
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute.ExportLanguageServiceAttribute(System.Type type, string language, string layer = "Default") -> void
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute.Language.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute.Layer.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceAttribute.ServiceType.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute.ExportLanguageServiceFactoryAttribute(System.Type type, string language, string layer = "Default") -> void
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute.Language.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute.Layer.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportLanguageServiceFactoryAttribute.ServiceType.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceAttribute
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceAttribute.ExportWorkspaceServiceAttribute(System.Type serviceType, string layer = "Default") -> void
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceAttribute.Layer.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceAttribute.ServiceType.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceFactoryAttribute
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceFactoryAttribute.ExportWorkspaceServiceFactoryAttribute(System.Type serviceType, string layer = "Default") -> void
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceFactoryAttribute.Layer.get -> string
Microsoft.CodeAnalysis.Host.Mef.ExportWorkspaceServiceFactoryAttribute.ServiceType.get -> string
Microsoft.CodeAnalysis.Host.Mef.ILanguageServiceFactory
Microsoft.CodeAnalysis.Host.Mef.ILanguageServiceFactory.CreateLanguageService(Microsoft.CodeAnalysis.Host.HostLanguageServices languageServices) -> Microsoft.CodeAnalysis.Host.ILanguageService
Microsoft.CodeAnalysis.Host.Mef.IWorkspaceServiceFactory
Microsoft.CodeAnalysis.Host.Mef.IWorkspaceServiceFactory.CreateService(Microsoft.CodeAnalysis.Host.HostWorkspaceServices workspaceServices) -> Microsoft.CodeAnalysis.Host.IWorkspaceService
Microsoft.CodeAnalysis.Host.Mef.MefHostServices
Microsoft.CodeAnalysis.Host.Mef.MefHostServices.MefHostServices(System.Composition.CompositionContext compositionContext) -> void
Microsoft.CodeAnalysis.Host.Mef.ServiceLayer
Microsoft.CodeAnalysis.Options.DocumentOptionSet
Microsoft.CodeAnalysis.Options.DocumentOptionSet.GetOption<T>(Microsoft.CodeAnalysis.Options.PerLanguageOption<T> option) -> T
Microsoft.CodeAnalysis.Options.DocumentOptionSet.WithChangedOption<T>(Microsoft.CodeAnalysis.Options.PerLanguageOption<T> option, T value) -> Microsoft.CodeAnalysis.Options.DocumentOptionSet
Microsoft.CodeAnalysis.Options.IOption
Microsoft.CodeAnalysis.Options.IOption.DefaultValue.get -> object
Microsoft.CodeAnalysis.Options.IOption.Feature.get -> string
Microsoft.CodeAnalysis.Options.IOption.IsPerLanguage.get -> bool
Microsoft.CodeAnalysis.Options.IOption.Name.get -> string
Microsoft.CodeAnalysis.Options.IOption.StorageLocations.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Options.OptionStorageLocation>
Microsoft.CodeAnalysis.Options.IOption.Type.get -> System.Type
Microsoft.CodeAnalysis.Options.Option<T>
Microsoft.CodeAnalysis.Options.Option<T>.DefaultValue.get -> T
Microsoft.CodeAnalysis.Options.Option<T>.Feature.get -> string
Microsoft.CodeAnalysis.Options.Option<T>.Name.get -> string
Microsoft.CodeAnalysis.Options.Option<T>.Option(string feature, string name) -> void
Microsoft.CodeAnalysis.Options.Option<T>.Option(string feature, string name, T defaultValue) -> void
Microsoft.CodeAnalysis.Options.Option<T>.Option(string feature, string name, T defaultValue, params Microsoft.CodeAnalysis.Options.OptionStorageLocation[] storageLocations) -> void
Microsoft.CodeAnalysis.Options.Option<T>.StorageLocations.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Options.OptionStorageLocation>
Microsoft.CodeAnalysis.Options.Option<T>.Type.get -> System.Type
Microsoft.CodeAnalysis.Options.OptionKey
Microsoft.CodeAnalysis.Options.OptionKey.Equals(Microsoft.CodeAnalysis.Options.OptionKey other) -> bool
Microsoft.CodeAnalysis.Options.OptionKey.Language.get -> string
Microsoft.CodeAnalysis.Options.OptionKey.Option.get -> Microsoft.CodeAnalysis.Options.IOption
Microsoft.CodeAnalysis.Options.OptionKey.OptionKey() -> void
Microsoft.CodeAnalysis.Options.OptionKey.OptionKey(Microsoft.CodeAnalysis.Options.IOption option, string language = null) -> void
Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Options.OptionSet.GetOption(Microsoft.CodeAnalysis.Options.OptionKey optionKey) -> object
Microsoft.CodeAnalysis.Options.OptionSet.GetOption<T>(Microsoft.CodeAnalysis.Options.Option<T> option) -> T
Microsoft.CodeAnalysis.Options.OptionSet.GetOption<T>(Microsoft.CodeAnalysis.Options.OptionKey optionKey) -> T
Microsoft.CodeAnalysis.Options.OptionSet.GetOption<T>(Microsoft.CodeAnalysis.Options.PerLanguageOption<T> option, string language) -> T
Microsoft.CodeAnalysis.Options.OptionSet.OptionSet() -> void
Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption<T>(Microsoft.CodeAnalysis.Options.Option<T> option, T value) -> Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Options.OptionSet.WithChangedOption<T>(Microsoft.CodeAnalysis.Options.PerLanguageOption<T> option, string language, T value) -> Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Options.OptionStorageLocation
Microsoft.CodeAnalysis.Options.OptionStorageLocation.OptionStorageLocation() -> void
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.DefaultValue.get -> T
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.Feature.get -> string
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.Name.get -> string
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.PerLanguageOption(string feature, string name, T defaultValue) -> void
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.PerLanguageOption(string feature, string name, T defaultValue, params Microsoft.CodeAnalysis.Options.OptionStorageLocation[] storageLocations) -> void
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.StorageLocations.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Options.OptionStorageLocation>
Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.Type.get -> System.Type
Microsoft.CodeAnalysis.PreservationMode
Microsoft.CodeAnalysis.PreservationMode.PreserveIdentity = 1 -> Microsoft.CodeAnalysis.PreservationMode
Microsoft.CodeAnalysis.PreservationMode.PreserveValue = 0 -> Microsoft.CodeAnalysis.PreservationMode
Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddAdditionalDocument(string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Project.AddAdditionalDocument(string name, string text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Project.AddAnalyzerConfigDocument(string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Project.AddAnalyzerReference(Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddDocument(string name, Microsoft.CodeAnalysis.SyntaxNode syntaxRoot, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.AddDocument(string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.AddDocument(string name, string text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.AdditionalDocumentIds.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.Project.AdditionalDocuments.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.TextDocument>
Microsoft.CodeAnalysis.Project.AddMetadataReference(Microsoft.CodeAnalysis.MetadataReference metadataReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddMetadataReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddProjectReference(Microsoft.CodeAnalysis.ProjectReference projectReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AddProjectReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.AllProjectReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.Project.AnalyzerConfigDocuments.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.AnalyzerConfigDocument>
Microsoft.CodeAnalysis.Project.AnalyzerOptions.get -> Microsoft.CodeAnalysis.Diagnostics.AnalyzerOptions
Microsoft.CodeAnalysis.Project.AnalyzerReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.Project.AssemblyName.get -> string
Microsoft.CodeAnalysis.Project.CompilationOptions.get -> Microsoft.CodeAnalysis.CompilationOptions
Microsoft.CodeAnalysis.Project.CompilationOutputInfo.get -> Microsoft.CodeAnalysis.CompilationOutputInfo
Microsoft.CodeAnalysis.Project.ContainsAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Project.ContainsAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Project.ContainsDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Project.DefaultNamespace.get -> string
Microsoft.CodeAnalysis.Project.DocumentIds.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.Project.Documents.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Document>
Microsoft.CodeAnalysis.Project.FilePath.get -> string
Microsoft.CodeAnalysis.Project.GetAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Project.GetAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.AnalyzerConfigDocument
Microsoft.CodeAnalysis.Project.GetChanges(Microsoft.CodeAnalysis.Project oldProject) -> Microsoft.CodeAnalysis.ProjectChanges
Microsoft.CodeAnalysis.Project.GetCompilationAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Compilation>
Microsoft.CodeAnalysis.Project.GetDependentSemanticVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Project.GetDependentVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Project.GetDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.GetDocument(Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Project.GetDocumentId(Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.Project.GetLatestDocumentVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Project.GetSemanticVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.Project.HasDocuments.get -> bool
Microsoft.CodeAnalysis.Project.Id.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.Project.IsSubmission.get -> bool
Microsoft.CodeAnalysis.Project.Language.get -> string
Microsoft.CodeAnalysis.Project.LanguageServices.get -> Microsoft.CodeAnalysis.Host.HostLanguageServices
Microsoft.CodeAnalysis.Project.MetadataReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.MetadataReference>
Microsoft.CodeAnalysis.Project.Name.get -> string
Microsoft.CodeAnalysis.Project.OutputFilePath.get -> string
Microsoft.CodeAnalysis.Project.OutputRefFilePath.get -> string
Microsoft.CodeAnalysis.Project.ParseOptions.get -> Microsoft.CodeAnalysis.ParseOptions
Microsoft.CodeAnalysis.Project.ProjectReferences.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.Project.RemoveAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveAdditionalDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveAnalyzerConfigDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveAnalyzerReference(Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveMetadataReference(Microsoft.CodeAnalysis.MetadataReference metadataReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.RemoveProjectReference(Microsoft.CodeAnalysis.ProjectReference projectReference) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.Solution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Project.SupportsCompilation.get -> bool
Microsoft.CodeAnalysis.Project.TryGetCompilation(out Microsoft.CodeAnalysis.Compilation compilation) -> bool
Microsoft.CodeAnalysis.Project.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.Project.WithAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferencs) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithAssemblyName(string assemblyName) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithCompilationOptions(Microsoft.CodeAnalysis.CompilationOptions options) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithDefaultNamespace(string defaultNamespace) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithMetadataReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithParseOptions(Microsoft.CodeAnalysis.ParseOptions options) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Project.WithProjectReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.ProjectChanges
Microsoft.CodeAnalysis.ProjectChanges.GetAddedAdditionalDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedAnalyzerConfigDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedAnalyzerReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedMetadataReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference>
Microsoft.CodeAnalysis.ProjectChanges.GetAddedProjectReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.ProjectChanges.GetChangedAdditionalDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetChangedAnalyzerConfigDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetChangedDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetChangedDocuments(bool onlyGetDocumentsWithTextChanges) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedAdditionalDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedAnalyzerConfigDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedAnalyzerReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedDocuments() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedMetadataReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference>
Microsoft.CodeAnalysis.ProjectChanges.GetRemovedProjectReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.ProjectChanges.NewProject.get -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.ProjectChanges.OldProject.get -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.ProjectChanges.ProjectChanges() -> void
Microsoft.CodeAnalysis.ProjectChanges.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectDependencyGraph
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetDependencySets(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectId>>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetProjectsThatDirectlyDependOnThisProject(Microsoft.CodeAnalysis.ProjectId projectId) -> System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetProjectsThatThisProjectDirectlyDependsOn(Microsoft.CodeAnalysis.ProjectId projectId) -> System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(Microsoft.CodeAnalysis.ProjectId projectId) -> System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(Microsoft.CodeAnalysis.ProjectId projectId) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDependencyGraph.GetTopologicallySortedProjects(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.ProjectDiagnostic
Microsoft.CodeAnalysis.ProjectDiagnostic.ProjectDiagnostic(Microsoft.CodeAnalysis.WorkspaceDiagnosticKind kind, string message, Microsoft.CodeAnalysis.ProjectId projectId) -> void
Microsoft.CodeAnalysis.ProjectDiagnostic.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectId.Equals(Microsoft.CodeAnalysis.ProjectId other) -> bool
Microsoft.CodeAnalysis.ProjectId.Id.get -> System.Guid
Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.AdditionalDocuments.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentInfo>
Microsoft.CodeAnalysis.ProjectInfo.AnalyzerConfigDocuments.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentInfo>
Microsoft.CodeAnalysis.ProjectInfo.AnalyzerReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.ProjectInfo.AssemblyName.get -> string
Microsoft.CodeAnalysis.ProjectInfo.CompilationOptions.get -> Microsoft.CodeAnalysis.CompilationOptions
Microsoft.CodeAnalysis.ProjectInfo.CompilationOutputInfo.get -> Microsoft.CodeAnalysis.CompilationOutputInfo
Microsoft.CodeAnalysis.ProjectInfo.Documents.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.DocumentInfo>
Microsoft.CodeAnalysis.ProjectInfo.FilePath.get -> string
Microsoft.CodeAnalysis.ProjectInfo.HostObjectType.get -> System.Type
Microsoft.CodeAnalysis.ProjectInfo.Id.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectInfo.IsSubmission.get -> bool
Microsoft.CodeAnalysis.ProjectInfo.Language.get -> string
Microsoft.CodeAnalysis.ProjectInfo.MetadataReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.MetadataReference>
Microsoft.CodeAnalysis.ProjectInfo.Name.get -> string
Microsoft.CodeAnalysis.ProjectInfo.OutputFilePath.get -> string
Microsoft.CodeAnalysis.ProjectInfo.OutputRefFilePath.get -> string
Microsoft.CodeAnalysis.ProjectInfo.ParseOptions.get -> Microsoft.CodeAnalysis.ParseOptions
Microsoft.CodeAnalysis.ProjectInfo.ProjectReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.ProjectReference>
Microsoft.CodeAnalysis.ProjectInfo.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.ProjectInfo.WithAdditionalDocuments(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> additionalDocuments) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithAnalyzerConfigDocuments(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> analyzerConfigDocuments) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithAssemblyName(string assemblyName) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithCompilationOptions(Microsoft.CodeAnalysis.CompilationOptions compilationOptions) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithCompilationOutputInfo(in Microsoft.CodeAnalysis.CompilationOutputInfo info) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithDefaultNamespace(string defaultNamespace) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithDocuments(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> documents) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithFilePath(string filePath) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithMetadataReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithName(string name) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithOutputFilePath(string outputFilePath) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithOutputRefFilePath(string outputRefFilePath) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithParseOptions(Microsoft.CodeAnalysis.ParseOptions parseOptions) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithProjectReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectInfo.WithVersion(Microsoft.CodeAnalysis.VersionStamp version) -> Microsoft.CodeAnalysis.ProjectInfo
Microsoft.CodeAnalysis.ProjectReference
Microsoft.CodeAnalysis.ProjectReference.Aliases.get -> System.Collections.Immutable.ImmutableArray<string>
Microsoft.CodeAnalysis.ProjectReference.EmbedInteropTypes.get -> bool
Microsoft.CodeAnalysis.ProjectReference.Equals(Microsoft.CodeAnalysis.ProjectReference reference) -> bool
Microsoft.CodeAnalysis.ProjectReference.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.ProjectReference.ProjectReference(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Immutable.ImmutableArray<string> aliases = default(System.Collections.Immutable.ImmutableArray<string>), bool embedInteropTypes = false) -> void
Microsoft.CodeAnalysis.Recommendations.RecommendationOptions
Microsoft.CodeAnalysis.Recommendations.Recommender
Microsoft.CodeAnalysis.Rename.RenameEntityKind
Microsoft.CodeAnalysis.Rename.RenameEntityKind.BaseSymbol = 0 -> Microsoft.CodeAnalysis.Rename.RenameEntityKind
Microsoft.CodeAnalysis.Rename.RenameEntityKind.OverloadedSymbols = 1 -> Microsoft.CodeAnalysis.Rename.RenameEntityKind
Microsoft.CodeAnalysis.Rename.RenameOptions
Microsoft.CodeAnalysis.Rename.Renamer
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction.GetErrors(System.Globalization.CultureInfo culture = null) -> System.Collections.Immutable.ImmutableArray<string>
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet.ApplicableActions.get -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction>
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet.UpdateSolutionAsync(Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAction> actions, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet.UpdateSolutionAsync(Microsoft.CodeAnalysis.Solution solution, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
Microsoft.CodeAnalysis.Simplification.SimplificationOptions
Microsoft.CodeAnalysis.Simplification.Simplifier
Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, string text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAdditionalDocument(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAdditionalDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentInfo> documentInfos) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerConfigDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentInfo> documentInfos) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerReference(Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.SyntaxNode syntaxRoot, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false, Microsoft.CodeAnalysis.PreservationMode preservationMode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.Text.SourceText text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null, bool isGenerated = false) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, Microsoft.CodeAnalysis.TextLoader loader, System.Collections.Generic.IEnumerable<string> folders = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentId documentId, string name, string text, System.Collections.Generic.IEnumerable<string> folders = null, string filePath = null) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocument(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentInfo> documentInfos) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddMetadataReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddMetadataReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddProject(Microsoft.CodeAnalysis.ProjectId projectId, string name, string assemblyName, string language) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddProject(Microsoft.CodeAnalysis.ProjectInfo projectInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddProject(string name, string assemblyName, string language) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Solution.AddProjectReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AddProjectReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.AnalyzerReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.Solution.ContainsAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Solution.ContainsAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Solution.ContainsDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
Microsoft.CodeAnalysis.Solution.ContainsProject(Microsoft.CodeAnalysis.ProjectId projectId) -> bool
Microsoft.CodeAnalysis.Solution.FilePath.get -> string
Microsoft.CodeAnalysis.Solution.GetAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.Solution.GetAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.AnalyzerConfigDocument
Microsoft.CodeAnalysis.Solution.GetChanges(Microsoft.CodeAnalysis.Solution oldSolution) -> Microsoft.CodeAnalysis.SolutionChanges
Microsoft.CodeAnalysis.Solution.GetDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Solution.GetDocument(Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> Microsoft.CodeAnalysis.Document
Microsoft.CodeAnalysis.Solution.GetDocumentId(Microsoft.CodeAnalysis.SyntaxTree syntaxTree) -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.Solution.GetDocumentId(Microsoft.CodeAnalysis.SyntaxTree syntaxTree, Microsoft.CodeAnalysis.ProjectId projectId) -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.Solution.GetDocumentIdsWithFilePath(string filePath) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId>
Microsoft.CodeAnalysis.Solution.GetIsolatedSolution() -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.GetLatestProjectVersion() -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.Solution.GetProject(Microsoft.CodeAnalysis.IAssemblySymbol assemblySymbol, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Solution.GetProject(Microsoft.CodeAnalysis.ProjectId projectId) -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.Solution.GetProjectDependencyGraph() -> Microsoft.CodeAnalysis.ProjectDependencyGraph
Microsoft.CodeAnalysis.Solution.Id.get -> Microsoft.CodeAnalysis.SolutionId
Microsoft.CodeAnalysis.Solution.Options.get -> Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Solution.ProjectIds.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.ProjectId>
Microsoft.CodeAnalysis.Solution.Projects.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Project>
Microsoft.CodeAnalysis.Solution.RemoveAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAdditionalDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAnalyzerConfigDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAnalyzerReference(Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveAnalyzerReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveDocuments(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveMetadataReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveProject(Microsoft.CodeAnalysis.ProjectId projectId) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.RemoveProjectReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.Solution.WithAdditionalDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAdditionalDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextAndVersion textAndVersion, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAdditionalDocumentTextLoader(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader, Microsoft.CodeAnalysis.PreservationMode mode) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAnalyzerConfigDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAnalyzerConfigDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextAndVersion textAndVersion, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAnalyzerConfigDocumentTextLoader(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader, Microsoft.CodeAnalysis.PreservationMode mode) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithAnalyzerReferences(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentFilePath(Microsoft.CodeAnalysis.DocumentId documentId, string filePath) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentFolders(Microsoft.CodeAnalysis.DocumentId documentId, System.Collections.Generic.IEnumerable<string> folders) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentName(Microsoft.CodeAnalysis.DocumentId documentId, string name) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentSourceCodeKind(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.SourceCodeKind sourceCodeKind) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentSyntaxRoot(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentText(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextAndVersion textAndVersion, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentText(System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId> documentIds, Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.PreservationMode mode = Microsoft.CodeAnalysis.PreservationMode.PreserveValue) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithDocumentTextLoader(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader, Microsoft.CodeAnalysis.PreservationMode mode) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithOptions(Microsoft.CodeAnalysis.Options.OptionSet options) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectAnalyzerReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectAssemblyName(Microsoft.CodeAnalysis.ProjectId projectId, string assemblyName) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectCompilationOptions(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.CompilationOptions options) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectCompilationOutputInfo(Microsoft.CodeAnalysis.ProjectId projectId, in Microsoft.CodeAnalysis.CompilationOutputInfo info) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectDefaultNamespace(Microsoft.CodeAnalysis.ProjectId projectId, string defaultNamespace) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectDocumentsOrder(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Immutable.ImmutableList<Microsoft.CodeAnalysis.DocumentId> documentIds) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectFilePath(Microsoft.CodeAnalysis.ProjectId projectId, string filePath) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectMetadataReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectName(Microsoft.CodeAnalysis.ProjectId projectId, string name) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectOutputFilePath(Microsoft.CodeAnalysis.ProjectId projectId, string outputFilePath) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectOutputRefFilePath(Microsoft.CodeAnalysis.ProjectId projectId, string outputRefFilePath) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectParseOptions(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ParseOptions options) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.WithProjectReferences(Microsoft.CodeAnalysis.ProjectId projectId, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Solution.Workspace.get -> Microsoft.CodeAnalysis.Workspace
Microsoft.CodeAnalysis.SolutionChanges
Microsoft.CodeAnalysis.SolutionChanges.GetAddedAnalyzerReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.SolutionChanges.GetAddedProjects() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Project>
Microsoft.CodeAnalysis.SolutionChanges.GetProjectChanges() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectChanges>
Microsoft.CodeAnalysis.SolutionChanges.GetRemovedAnalyzerReferences() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.SolutionChanges.GetRemovedProjects() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Project>
Microsoft.CodeAnalysis.SolutionChanges.SolutionChanges() -> void
Microsoft.CodeAnalysis.SolutionId
Microsoft.CodeAnalysis.SolutionId.Equals(Microsoft.CodeAnalysis.SolutionId other) -> bool
Microsoft.CodeAnalysis.SolutionId.Id.get -> System.Guid
Microsoft.CodeAnalysis.SolutionInfo
Microsoft.CodeAnalysis.SolutionInfo.AnalyzerReferences.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference>
Microsoft.CodeAnalysis.SolutionInfo.FilePath.get -> string
Microsoft.CodeAnalysis.SolutionInfo.Id.get -> Microsoft.CodeAnalysis.SolutionId
Microsoft.CodeAnalysis.SolutionInfo.Projects.get -> System.Collections.Generic.IReadOnlyList<Microsoft.CodeAnalysis.ProjectInfo>
Microsoft.CodeAnalysis.SolutionInfo.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.Tags.WellKnownTags
Microsoft.CodeAnalysis.TextAndVersion
Microsoft.CodeAnalysis.TextAndVersion.FilePath.get -> string
Microsoft.CodeAnalysis.TextAndVersion.Text.get -> Microsoft.CodeAnalysis.Text.SourceText
Microsoft.CodeAnalysis.TextAndVersion.Version.get -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.TextDocument
Microsoft.CodeAnalysis.TextDocument.FilePath.get -> string
Microsoft.CodeAnalysis.TextDocument.Folders.get -> System.Collections.Generic.IReadOnlyList<string>
Microsoft.CodeAnalysis.TextDocument.GetTextAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Text.SourceText>
Microsoft.CodeAnalysis.TextDocument.GetTextVersionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.VersionStamp>
Microsoft.CodeAnalysis.TextDocument.Id.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.TextDocument.Name.get -> string
Microsoft.CodeAnalysis.TextDocument.Project.get -> Microsoft.CodeAnalysis.Project
Microsoft.CodeAnalysis.TextDocument.TryGetText(out Microsoft.CodeAnalysis.Text.SourceText text) -> bool
Microsoft.CodeAnalysis.TextDocument.TryGetTextVersion(out Microsoft.CodeAnalysis.VersionStamp version) -> bool
Microsoft.CodeAnalysis.TextDocumentKind
Microsoft.CodeAnalysis.TextDocumentKind.AdditionalDocument = 1 -> Microsoft.CodeAnalysis.TextDocumentKind
Microsoft.CodeAnalysis.TextDocumentKind.AnalyzerConfigDocument = 2 -> Microsoft.CodeAnalysis.TextDocumentKind
Microsoft.CodeAnalysis.TextDocumentKind.Document = 0 -> Microsoft.CodeAnalysis.TextDocumentKind
Microsoft.CodeAnalysis.TextLoader
Microsoft.CodeAnalysis.TextLoader.TextLoader() -> void
Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.VersionStamp.Equals(Microsoft.CodeAnalysis.VersionStamp version) -> bool
Microsoft.CodeAnalysis.VersionStamp.GetNewerVersion() -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.VersionStamp.GetNewerVersion(Microsoft.CodeAnalysis.VersionStamp version) -> Microsoft.CodeAnalysis.VersionStamp
Microsoft.CodeAnalysis.VersionStamp.VersionStamp() -> void
Microsoft.CodeAnalysis.Workspace
Microsoft.CodeAnalysis.Workspace.CheckAdditionalDocumentIsInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckAdditionalDocumentIsNotInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckAnalyzerConfigDocumentIsInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckAnalyzerConfigDocumentIsNotInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckCanOpenDocuments() -> void
Microsoft.CodeAnalysis.Workspace.CheckDocumentIsClosed(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckDocumentIsInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckDocumentIsNotInCurrentSolution(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckDocumentIsOpen(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotContainOpenDocuments(Microsoft.CodeAnalysis.ProjectId projectId) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotHaveAnalyzerReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotHaveMetadataReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotHaveProjectReference(Microsoft.CodeAnalysis.ProjectId fromProjectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectDoesNotHaveTransitiveProjectReference(Microsoft.CodeAnalysis.ProjectId fromProjectId, Microsoft.CodeAnalysis.ProjectId toProjectId) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectHasAnalyzerReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectHasMetadataReference(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectHasProjectReference(Microsoft.CodeAnalysis.ProjectId fromProjectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectIsInCurrentSolution(Microsoft.CodeAnalysis.ProjectId projectId) -> void
Microsoft.CodeAnalysis.Workspace.CheckProjectIsNotInCurrentSolution(Microsoft.CodeAnalysis.ProjectId projectId) -> void
Microsoft.CodeAnalysis.Workspace.CheckSolutionIsEmpty() -> void
Microsoft.CodeAnalysis.Workspace.ClearOpenDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.ClearOpenDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool isSolutionClosing) -> void
Microsoft.CodeAnalysis.Workspace.ClearSolution() -> void
Microsoft.CodeAnalysis.Workspace.CreateSolution(Microsoft.CodeAnalysis.SolutionId id) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Workspace.CreateSolution(Microsoft.CodeAnalysis.SolutionInfo solutionInfo) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Workspace.CurrentSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Workspace.Dispose() -> void
Microsoft.CodeAnalysis.Workspace.DocumentActiveContextChanged -> System.EventHandler<Microsoft.CodeAnalysis.DocumentActiveContextChangedEventArgs>
Microsoft.CodeAnalysis.Workspace.DocumentClosed -> System.EventHandler<Microsoft.CodeAnalysis.DocumentEventArgs>
Microsoft.CodeAnalysis.Workspace.DocumentOpened -> System.EventHandler<Microsoft.CodeAnalysis.DocumentEventArgs>
Microsoft.CodeAnalysis.Workspace.Kind.get -> string
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentClosed(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader reloader) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentOpened(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer, bool isCurrentContext = true) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText newText, Microsoft.CodeAnalysis.PreservationMode mode) -> void
Microsoft.CodeAnalysis.Workspace.OnAdditionalDocumentTextLoaderChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentClosed(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader reloader) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentOpened(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer, bool isCurrentContext = true) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText newText, Microsoft.CodeAnalysis.PreservationMode mode) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerConfigDocumentTextLoaderChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
Microsoft.CodeAnalysis.Workspace.OnAnalyzerReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
Microsoft.CodeAnalysis.Workspace.OnAssemblyNameChanged(Microsoft.CodeAnalysis.ProjectId projectId, string assemblyName) -> void
Microsoft.CodeAnalysis.Workspace.OnCompilationOptionsChanged(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.CompilationOptions options) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo documentInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentClosed(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader reloader, bool updateActiveContext = false) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentContextUpdated(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentInfoChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.DocumentInfo newInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentOpened(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer, bool isCurrentContext = true) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentReloaded(Microsoft.CodeAnalysis.DocumentInfo newDocumentInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentsAdded(System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DocumentInfo> documentInfos) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentSourceCodeKindChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.SourceCodeKind sourceCodeKind) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.Text.SourceText newText, Microsoft.CodeAnalysis.PreservationMode mode) -> void
Microsoft.CodeAnalysis.Workspace.OnDocumentTextLoaderChanged(Microsoft.CodeAnalysis.DocumentId documentId, Microsoft.CodeAnalysis.TextLoader loader) -> void
Microsoft.CodeAnalysis.Workspace.OnMetadataReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
Microsoft.CodeAnalysis.Workspace.OnMetadataReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
Microsoft.CodeAnalysis.Workspace.OnOutputFilePathChanged(Microsoft.CodeAnalysis.ProjectId projectId, string outputFilePath) -> void
Microsoft.CodeAnalysis.Workspace.OnOutputRefFilePathChanged(Microsoft.CodeAnalysis.ProjectId projectId, string outputFilePath) -> void
Microsoft.CodeAnalysis.Workspace.OnParseOptionsChanged(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ParseOptions options) -> void
Microsoft.CodeAnalysis.Workspace.OnProjectAdded(Microsoft.CodeAnalysis.ProjectInfo projectInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnProjectNameChanged(Microsoft.CodeAnalysis.ProjectId projectId, string name, string filePath) -> void
Microsoft.CodeAnalysis.Workspace.OnProjectReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
Microsoft.CodeAnalysis.Workspace.OnProjectReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
Microsoft.CodeAnalysis.Workspace.OnSolutionAdded(Microsoft.CodeAnalysis.SolutionInfo solutionInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnSolutionReloaded(Microsoft.CodeAnalysis.SolutionInfo reloadedSolutionInfo) -> void
Microsoft.CodeAnalysis.Workspace.OnSolutionRemoved() -> void
Microsoft.CodeAnalysis.Workspace.Options.get -> Microsoft.CodeAnalysis.Options.OptionSet
Microsoft.CodeAnalysis.Workspace.Options.set -> void
Microsoft.CodeAnalysis.Workspace.RaiseDocumentActiveContextChangedEventAsync(Microsoft.CodeAnalysis.Document document) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RaiseDocumentActiveContextChangedEventAsync(Microsoft.CodeAnalysis.Text.SourceTextContainer sourceTextContainer, Microsoft.CodeAnalysis.DocumentId oldActiveContextDocumentId, Microsoft.CodeAnalysis.DocumentId newActiveContextDocumentId) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RaiseDocumentClosedEventAsync(Microsoft.CodeAnalysis.Document document) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RaiseDocumentOpenedEventAsync(Microsoft.CodeAnalysis.Document document) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RaiseWorkspaceChangedEventAsync(Microsoft.CodeAnalysis.WorkspaceChangeKind kind, Microsoft.CodeAnalysis.Solution oldSolution, Microsoft.CodeAnalysis.Solution newSolution, Microsoft.CodeAnalysis.ProjectId projectId = null, Microsoft.CodeAnalysis.DocumentId documentId = null) -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.RegisterText(Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer) -> void
Microsoft.CodeAnalysis.Workspace.ScheduleTask(System.Action action, string taskName = "Workspace.Task") -> System.Threading.Tasks.Task
Microsoft.CodeAnalysis.Workspace.ScheduleTask<T>(System.Func<T> func, string taskName = "Workspace.Task") -> System.Threading.Tasks.Task<T>
Microsoft.CodeAnalysis.Workspace.Services.get -> Microsoft.CodeAnalysis.Host.HostWorkspaceServices
Microsoft.CodeAnalysis.Workspace.SetCurrentSolution(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.Workspace.UnregisterText(Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer) -> void
Microsoft.CodeAnalysis.Workspace.UpdateReferencesAfterAdd() -> void
Microsoft.CodeAnalysis.Workspace.Workspace(Microsoft.CodeAnalysis.Host.HostServices host, string workspaceKind) -> void
Microsoft.CodeAnalysis.Workspace.WorkspaceChanged -> System.EventHandler<Microsoft.CodeAnalysis.WorkspaceChangeEventArgs>
Microsoft.CodeAnalysis.Workspace.WorkspaceFailed -> System.EventHandler<Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs>
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.DocumentId.get -> Microsoft.CodeAnalysis.DocumentId
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.Kind.get -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.NewSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.OldSolution.get -> Microsoft.CodeAnalysis.Solution
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.ProjectId.get -> Microsoft.CodeAnalysis.ProjectId
Microsoft.CodeAnalysis.WorkspaceChangeEventArgs.WorkspaceChangeEventArgs(Microsoft.CodeAnalysis.WorkspaceChangeKind kind, Microsoft.CodeAnalysis.Solution oldSolution, Microsoft.CodeAnalysis.Solution newSolution, Microsoft.CodeAnalysis.ProjectId projectId = null, Microsoft.CodeAnalysis.DocumentId documentId = null) -> void
Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AdditionalDocumentAdded = 13 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AdditionalDocumentChanged = 16 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AdditionalDocumentReloaded = 15 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AdditionalDocumentRemoved = 14 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AnalyzerConfigDocumentAdded = 18 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AnalyzerConfigDocumentChanged = 21 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AnalyzerConfigDocumentReloaded = 20 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.AnalyzerConfigDocumentRemoved = 19 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentAdded = 9 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentChanged = 12 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentInfoChanged = 17 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentReloaded = 11 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.DocumentRemoved = 10 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.ProjectAdded = 5 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.ProjectChanged = 7 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.ProjectReloaded = 8 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.ProjectRemoved = 6 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionAdded = 1 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionChanged = 0 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionCleared = 3 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionReloaded = 4 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceChangeKind.SolutionRemoved = 2 -> Microsoft.CodeAnalysis.WorkspaceChangeKind
Microsoft.CodeAnalysis.WorkspaceDiagnostic
Microsoft.CodeAnalysis.WorkspaceDiagnostic.Kind.get -> Microsoft.CodeAnalysis.WorkspaceDiagnosticKind
Microsoft.CodeAnalysis.WorkspaceDiagnostic.Message.get -> string
Microsoft.CodeAnalysis.WorkspaceDiagnostic.WorkspaceDiagnostic(Microsoft.CodeAnalysis.WorkspaceDiagnosticKind kind, string message) -> void
Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs
Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs.Diagnostic.get -> Microsoft.CodeAnalysis.WorkspaceDiagnostic
Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs.WorkspaceDiagnosticEventArgs(Microsoft.CodeAnalysis.WorkspaceDiagnostic diagnostic) -> void
Microsoft.CodeAnalysis.WorkspaceDiagnosticKind
Microsoft.CodeAnalysis.WorkspaceDiagnosticKind.Failure = 0 -> Microsoft.CodeAnalysis.WorkspaceDiagnosticKind
Microsoft.CodeAnalysis.WorkspaceDiagnosticKind.Warning = 1 -> Microsoft.CodeAnalysis.WorkspaceDiagnosticKind
Microsoft.CodeAnalysis.WorkspaceKind
Microsoft.CodeAnalysis.WorkspaceRegistration
Microsoft.CodeAnalysis.WorkspaceRegistration.Workspace.get -> Microsoft.CodeAnalysis.Workspace
Microsoft.CodeAnalysis.WorkspaceRegistration.WorkspaceChanged -> System.EventHandler
Microsoft.CodeAnalysis.XmlDocumentationProvider
Microsoft.CodeAnalysis.XmlDocumentationProvider.XmlDocumentationProvider() -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.CanApplyChange(Microsoft.CodeAnalysis.ApplyChangesKind feature) -> bool
override Microsoft.CodeAnalysis.AdhocWorkspace.CanOpenDocuments.get -> bool
override Microsoft.CodeAnalysis.AdhocWorkspace.CloseAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.CloseAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.CloseDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.OpenAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.OpenAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
override Microsoft.CodeAnalysis.AdhocWorkspace.OpenDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
override Microsoft.CodeAnalysis.Classification.ClassifiedSpan.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Classification.ClassifiedSpan.GetHashCode() -> int
override Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation.Apply(Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken) -> void
override Microsoft.CodeAnalysis.CodeActions.CodeActionWithOptions.ComputeOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
override Microsoft.CodeAnalysis.CodeActions.OpenDocumentOperation.Apply(Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken) -> void
override Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.GetHashCode() -> int
override Microsoft.CodeAnalysis.CodeStyle.NotificationOption.ToString() -> string
override Microsoft.CodeAnalysis.CompilationOutputInfo.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.CompilationOutputInfo.GetHashCode() -> int
override Microsoft.CodeAnalysis.Differencing.Edit<TNode>.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Differencing.Edit<TNode>.GetHashCode() -> int
override Microsoft.CodeAnalysis.DocumentId.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.DocumentId.GetHashCode() -> int
override Microsoft.CodeAnalysis.DocumentId.ToString() -> string
override Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Editing.DeclarationModifiers.GetHashCode() -> int
override Microsoft.CodeAnalysis.Editing.DeclarationModifiers.ToString() -> string
override Microsoft.CodeAnalysis.FileTextLoader.LoadTextAndVersionAsync(Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.DocumentId documentId, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.TextAndVersion>
override Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.GetHashCode() -> int
override Microsoft.CodeAnalysis.Host.Mef.MefHostServices.CreateWorkspaceServices(Microsoft.CodeAnalysis.Workspace workspace) -> Microsoft.CodeAnalysis.Host.HostWorkspaceServices
override Microsoft.CodeAnalysis.Options.DocumentOptionSet.WithChangedOption(Microsoft.CodeAnalysis.Options.OptionKey optionAndLanguage, object value) -> Microsoft.CodeAnalysis.Options.OptionSet
override Microsoft.CodeAnalysis.Options.Option<T>.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Options.Option<T>.GetHashCode() -> int
override Microsoft.CodeAnalysis.Options.Option<T>.ToString() -> string
override Microsoft.CodeAnalysis.Options.OptionKey.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Options.OptionKey.GetHashCode() -> int
override Microsoft.CodeAnalysis.Options.OptionKey.ToString() -> string
override Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.GetHashCode() -> int
override Microsoft.CodeAnalysis.Options.PerLanguageOption<T>.ToString() -> string
override Microsoft.CodeAnalysis.ProjectId.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.ProjectId.GetHashCode() -> int
override Microsoft.CodeAnalysis.ProjectId.ToString() -> string
override Microsoft.CodeAnalysis.ProjectReference.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.ProjectReference.GetHashCode() -> int
override Microsoft.CodeAnalysis.SolutionId.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.SolutionId.GetHashCode() -> int
override Microsoft.CodeAnalysis.VersionStamp.Equals(object obj) -> bool
override Microsoft.CodeAnalysis.VersionStamp.GetHashCode() -> int
override Microsoft.CodeAnalysis.VersionStamp.ToString() -> string
override Microsoft.CodeAnalysis.WorkspaceDiagnostic.ToString() -> string
override Microsoft.CodeAnalysis.XmlDocumentationProvider.GetDocumentationForSymbol(string documentationMemberID, System.Globalization.CultureInfo preferredCulture, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> string
static Microsoft.CodeAnalysis.Classification.ClassificationTypeNames.AdditiveTypeNames.get -> System.Collections.Immutable.ImmutableArray<string>
static Microsoft.CodeAnalysis.Classification.Classifier.GetClassifiedSpans(Microsoft.CodeAnalysis.SemanticModel semanticModel, Microsoft.CodeAnalysis.Text.TextSpan textSpan, Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Classification.ClassifiedSpan>
static Microsoft.CodeAnalysis.Classification.Classifier.GetClassifiedSpansAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan textSpan, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Classification.ClassifiedSpan>>
static Microsoft.CodeAnalysis.CodeActions.CodeAction.Create(string title, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.CodeActions.CodeAction> nestedActions, bool isInlinable) -> Microsoft.CodeAnalysis.CodeActions.CodeAction
static Microsoft.CodeAnalysis.CodeActions.CodeAction.Create(string title, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>> createChangedDocument, string equivalenceKey = null) -> Microsoft.CodeAnalysis.CodeActions.CodeAction
static Microsoft.CodeAnalysis.CodeActions.CodeAction.Create(string title, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>> createChangedSolution, string equivalenceKey = null) -> Microsoft.CodeAnalysis.CodeActions.CodeAction
static Microsoft.CodeAnalysis.CodeActions.ConflictAnnotation.Create(string description) -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.CodeActions.ConflictAnnotation.GetDescription(Microsoft.CodeAnalysis.SyntaxAnnotation annotation) -> string
static Microsoft.CodeAnalysis.CodeActions.RenameAnnotation.Create() -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.CodeActions.WarningAnnotation.Create(string description) -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.CodeActions.WarningAnnotation.GetDescription(Microsoft.CodeAnalysis.SyntaxAnnotation annotation) -> string
static Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders.BatchFixer.get -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
static Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.Default.get -> Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>
static Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>.FromXElement(System.Xml.Linq.XElement element) -> Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<T>
static Microsoft.CodeAnalysis.CompilationOutputInfo.operator !=(in Microsoft.CodeAnalysis.CompilationOutputInfo left, in Microsoft.CodeAnalysis.CompilationOutputInfo right) -> bool
static Microsoft.CodeAnalysis.CompilationOutputInfo.operator ==(in Microsoft.CodeAnalysis.CompilationOutputInfo left, in Microsoft.CodeAnalysis.CompilationOutputInfo right) -> bool
static Microsoft.CodeAnalysis.DocumentId.CreateFromSerialized(Microsoft.CodeAnalysis.ProjectId projectId, System.Guid id, string debugName = null) -> Microsoft.CodeAnalysis.DocumentId
static Microsoft.CodeAnalysis.DocumentId.CreateNewId(Microsoft.CodeAnalysis.ProjectId projectId, string debugName = null) -> Microsoft.CodeAnalysis.DocumentId
static Microsoft.CodeAnalysis.DocumentId.operator !=(Microsoft.CodeAnalysis.DocumentId left, Microsoft.CodeAnalysis.DocumentId right) -> bool
static Microsoft.CodeAnalysis.DocumentId.operator ==(Microsoft.CodeAnalysis.DocumentId left, Microsoft.CodeAnalysis.DocumentId right) -> bool
static Microsoft.CodeAnalysis.DocumentInfo.Create(Microsoft.CodeAnalysis.DocumentId id, string name, System.Collections.Generic.IEnumerable<string> folders = null, Microsoft.CodeAnalysis.SourceCodeKind sourceCodeKind = Microsoft.CodeAnalysis.SourceCodeKind.Regular, Microsoft.CodeAnalysis.TextLoader loader = null, string filePath = null, bool isGenerated = false) -> Microsoft.CodeAnalysis.DocumentInfo
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Abstract.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Async.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Const.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Extern.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.From(Microsoft.CodeAnalysis.ISymbol symbol) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.New.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.None.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator !=(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> bool
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator &(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator +(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator -(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator ==(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> bool
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.operator |(Microsoft.CodeAnalysis.Editing.DeclarationModifiers left, Microsoft.CodeAnalysis.Editing.DeclarationModifiers right) -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Override.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Partial.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.ReadOnly.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Ref.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Sealed.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Static.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.TryParse(string value, out Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> bool
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Unsafe.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Virtual.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.Volatile.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WithEvents.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DeclarationModifiers.WriteOnly.get -> Microsoft.CodeAnalysis.Editing.DeclarationModifiers
static Microsoft.CodeAnalysis.Editing.DocumentEditor.CreateAsync(Microsoft.CodeAnalysis.Document document, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Editing.DocumentEditor>
static Microsoft.CodeAnalysis.Editing.ImportAdder.AddImportsAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Editing.ImportAdder.AddImportsAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.SyntaxAnnotation annotation, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Editing.ImportAdder.AddImportsAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Editing.ImportAdder.AddImportsAsync(Microsoft.CodeAnalysis.Document document, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Editing.SymbolEditor.Create(Microsoft.CodeAnalysis.Document document) -> Microsoft.CodeAnalysis.Editing.SymbolEditor
static Microsoft.CodeAnalysis.Editing.SymbolEditor.Create(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.Editing.SymbolEditor
static Microsoft.CodeAnalysis.Editing.SymbolEditorExtensions.GetBaseOrInterfaceDeclarationReferenceAsync(this Microsoft.CodeAnalysis.Editing.SymbolEditor editor, Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.ITypeSymbol baseOrInterfaceType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxNode>
static Microsoft.CodeAnalysis.Editing.SymbolEditorExtensions.SetBaseTypeAsync(this Microsoft.CodeAnalysis.Editing.SymbolEditor editor, Microsoft.CodeAnalysis.INamedTypeSymbol symbol, Microsoft.CodeAnalysis.ITypeSymbol newBaseType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.Editing.SymbolEditorExtensions.SetBaseTypeAsync(this Microsoft.CodeAnalysis.Editing.SymbolEditor editor, Microsoft.CodeAnalysis.INamedTypeSymbol symbol, System.Func<Microsoft.CodeAnalysis.Editing.SyntaxGenerator, Microsoft.CodeAnalysis.SyntaxNode> getNewBaseType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddAttribute(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode attribute) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddAttributeArgument(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode attributeDeclaration, Microsoft.CodeAnalysis.SyntaxNode attributeArgument) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddBaseType(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode baseType) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddInterfaceType(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode interfaceType) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddMember(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode member) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddParameter(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode parameter) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.AddReturnAttribute(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode attribute) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.InsertMembers(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, int index, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> members) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.InsertParameter(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, int index, Microsoft.CodeAnalysis.SyntaxNode parameter) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetAccessibility(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Accessibility accessibility) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetExpression(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode expression) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetGetAccessorStatements(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetModifiers(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetName(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, string name) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetSetAccessorStatements(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetStatements(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetType(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, Microsoft.CodeAnalysis.SyntaxNode type) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetTypeConstraint(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, string typeParameterName, Microsoft.CodeAnalysis.Editing.SpecialTypeConstraintKind kind, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> types) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxEditorExtensions.SetTypeParameters(this Microsoft.CodeAnalysis.Editing.SyntaxEditor editor, Microsoft.CodeAnalysis.SyntaxNode declaration, System.Collections.Generic.IEnumerable<string> typeParameters) -> void
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.DefaultRemoveOptions -> Microsoft.CodeAnalysis.SyntaxRemoveOptions
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGenerator(Microsoft.CodeAnalysis.Document document) -> Microsoft.CodeAnalysis.Editing.SyntaxGenerator
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGenerator(Microsoft.CodeAnalysis.Project project) -> Microsoft.CodeAnalysis.Editing.SyntaxGenerator
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.GetGenerator(Microsoft.CodeAnalysis.Workspace workspace, string language) -> Microsoft.CodeAnalysis.Editing.SyntaxGenerator
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.PreserveTrivia<TNode>(TNode node, System.Func<TNode, Microsoft.CodeAnalysis.SyntaxNode> nodeChanger) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveRange<TNode>(Microsoft.CodeAnalysis.SeparatedSyntaxList<TNode> list, int offset, int count) -> Microsoft.CodeAnalysis.SeparatedSyntaxList<TNode>
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveRange<TNode>(Microsoft.CodeAnalysis.SyntaxList<TNode> list, int offset, int count) -> Microsoft.CodeAnalysis.SyntaxList<TNode>
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceRange(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> replacements) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceWithTrivia(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode original, Microsoft.CodeAnalysis.SyntaxNode replacement) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceWithTrivia(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxToken original, Microsoft.CodeAnalysis.SyntaxToken replacement) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceWithTrivia<TNode>(Microsoft.CodeAnalysis.SyntaxNode root, TNode original, System.Func<TNode, Microsoft.CodeAnalysis.SyntaxNode> replacer) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.operator !=(Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation left, Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation right) -> bool
static Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation.operator ==(Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation left, Microsoft.CodeAnalysis.FindSymbols.ReferenceLocation right) -> bool
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindCallersAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Document> documents, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindCallersAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.SymbolCallerInfo>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDeclarationsAsync(Microsoft.CodeAnalysis.Project project, string name, bool ignoreCase, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDeclarationsAsync(Microsoft.CodeAnalysis.Project project, string name, bool ignoreCase, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDerivedClassesAsync(Microsoft.CodeAnalysis.INamedTypeSymbol type, Microsoft.CodeAnalysis.Solution solution, bool transitive = true, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.INamedTypeSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDerivedClassesAsync(Microsoft.CodeAnalysis.INamedTypeSymbol type, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.INamedTypeSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindDerivedInterfacesAsync(Microsoft.CodeAnalysis.INamedTypeSymbol type, Microsoft.CodeAnalysis.Solution solution, bool transitive = true, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.INamedTypeSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindImplementationsAsync(Microsoft.CodeAnalysis.INamedTypeSymbol type, Microsoft.CodeAnalysis.Solution solution, bool transitive = true, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.INamedTypeSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindImplementationsAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindImplementedInterfaceMembersAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindOverridesAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Project> projects = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindReferencesAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, Microsoft.CodeAnalysis.FindSymbols.IFindReferencesProgress progress, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Document> documents, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindReferencesAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Collections.Immutable.IImmutableSet<Microsoft.CodeAnalysis.Document> documents, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindReferencesAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.FindSymbols.ReferencedSymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSimilarSymbols<TSymbol>(TSymbol symbol, Microsoft.CodeAnalysis.Compilation compilation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<TSymbol>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Project project, string name, bool ignoreCase, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Project project, string name, bool ignoreCase, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Project project, System.Func<string, bool> predicate, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Project project, System.Func<string, bool> predicate, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Solution solution, string name, bool ignoreCase, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Solution solution, string name, bool ignoreCase, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Solution solution, System.Func<string, bool> predicate, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsAsync(Microsoft.CodeAnalysis.Solution solution, System.Func<string, bool> predicate, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsWithPatternAsync(Microsoft.CodeAnalysis.Project project, string pattern, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsWithPatternAsync(Microsoft.CodeAnalysis.Project project, string pattern, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsWithPatternAsync(Microsoft.CodeAnalysis.Solution solution, string pattern, Microsoft.CodeAnalysis.SymbolFilter filter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDeclarationsWithPatternAsync(Microsoft.CodeAnalysis.Solution solution, string pattern, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSourceDefinitionAsync(Microsoft.CodeAnalysis.ISymbol symbol, Microsoft.CodeAnalysis.Solution solution, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSymbolAtPosition(Microsoft.CodeAnalysis.SemanticModel semanticModel, int position, Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.ISymbol
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSymbolAtPositionAsync(Microsoft.CodeAnalysis.Document document, int position, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSymbolAtPositionAsync(Microsoft.CodeAnalysis.SemanticModel semanticModel, int position, Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.Formatting.Formatter.Annotation.get -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxAnnotation annotation, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Formatting.Formatter.Format(Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxNode
static Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.SyntaxAnnotation annotation, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(Microsoft.CodeAnalysis.Document document, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IList<Microsoft.CodeAnalysis.Text.TextChange>
static Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IList<Microsoft.CodeAnalysis.Text.TextChange>
static Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IList<Microsoft.CodeAnalysis.Text.TextChange>
static Microsoft.CodeAnalysis.Formatting.Formatter.OrganizeImportsAsync(Microsoft.CodeAnalysis.Document document, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<int>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.NewLine.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<string>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.SmartIndent.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<int>
static Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create(System.Collections.Generic.IEnumerable<System.Reflection.Assembly> assemblies) -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices
static Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create(System.Composition.CompositionContext compositionContext) -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices
static Microsoft.CodeAnalysis.Host.Mef.MefHostServices.DefaultAssemblies.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Assembly>
static Microsoft.CodeAnalysis.Host.Mef.MefHostServices.DefaultHost.get -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices
static Microsoft.CodeAnalysis.Options.Option<T>.implicit operator Microsoft.CodeAnalysis.Options.OptionKey(Microsoft.CodeAnalysis.Options.Option<T> option) -> Microsoft.CodeAnalysis.Options.OptionKey
static Microsoft.CodeAnalysis.Options.OptionKey.operator !=(Microsoft.CodeAnalysis.Options.OptionKey left, Microsoft.CodeAnalysis.Options.OptionKey right) -> bool
static Microsoft.CodeAnalysis.Options.OptionKey.operator ==(Microsoft.CodeAnalysis.Options.OptionKey left, Microsoft.CodeAnalysis.Options.OptionKey right) -> bool
static Microsoft.CodeAnalysis.ProjectId.CreateFromSerialized(System.Guid id, string debugName = null) -> Microsoft.CodeAnalysis.ProjectId
static Microsoft.CodeAnalysis.ProjectId.CreateNewId(string debugName = null) -> Microsoft.CodeAnalysis.ProjectId
static Microsoft.CodeAnalysis.ProjectId.operator !=(Microsoft.CodeAnalysis.ProjectId left, Microsoft.CodeAnalysis.ProjectId right) -> bool
static Microsoft.CodeAnalysis.ProjectId.operator ==(Microsoft.CodeAnalysis.ProjectId left, Microsoft.CodeAnalysis.ProjectId right) -> bool
static Microsoft.CodeAnalysis.ProjectInfo.Create(Microsoft.CodeAnalysis.ProjectId id, Microsoft.CodeAnalysis.VersionStamp version, string name, string assemblyName, string language, string filePath = null, string outputFilePath = null, Microsoft.CodeAnalysis.CompilationOptions compilationOptions = null, Microsoft.CodeAnalysis.ParseOptions parseOptions = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> documents = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> additionalDocuments = null, bool isSubmission = false, System.Type hostObjectType = null, string outputRefFilePath = null) -> Microsoft.CodeAnalysis.ProjectInfo
static Microsoft.CodeAnalysis.ProjectInfo.Create(Microsoft.CodeAnalysis.ProjectId id, Microsoft.CodeAnalysis.VersionStamp version, string name, string assemblyName, string language, string filePath, string outputFilePath, Microsoft.CodeAnalysis.CompilationOptions compilationOptions, Microsoft.CodeAnalysis.ParseOptions parseOptions, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> documents, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectReference> projectReferences, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.MetadataReference> metadataReferences, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentInfo> additionalDocuments, bool isSubmission, System.Type hostObjectType) -> Microsoft.CodeAnalysis.ProjectInfo
static Microsoft.CodeAnalysis.ProjectReference.operator !=(Microsoft.CodeAnalysis.ProjectReference left, Microsoft.CodeAnalysis.ProjectReference right) -> bool
static Microsoft.CodeAnalysis.ProjectReference.operator ==(Microsoft.CodeAnalysis.ProjectReference left, Microsoft.CodeAnalysis.ProjectReference right) -> bool
static Microsoft.CodeAnalysis.Recommendations.RecommendationOptions.FilterOutOfScopeLocals.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Recommendations.RecommendationOptions.HideAdvancedMembers.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Recommendations.Recommender.GetRecommendedSymbolsAtPosition(Microsoft.CodeAnalysis.SemanticModel semanticModel, int position, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>
static Microsoft.CodeAnalysis.Recommendations.Recommender.GetRecommendedSymbolsAtPositionAsync(Microsoft.CodeAnalysis.SemanticModel semanticModel, int position, Microsoft.CodeAnalysis.Workspace workspace, Microsoft.CodeAnalysis.Options.OptionSet options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ISymbol>>
static Microsoft.CodeAnalysis.Rename.RenameOptions.PreviewChanges.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Rename.RenameOptions.RenameInComments.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Rename.RenameOptions.RenameInStrings.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Rename.RenameOptions.RenameOverloads.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentAsync(Microsoft.CodeAnalysis.Document document, string newDocumentName, System.Collections.Generic.IReadOnlyList<string> newDocumentFolders = null, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Rename.Renamer.RenameDocumentActionSet>
static Microsoft.CodeAnalysis.Rename.Renamer.RenameSymbolAsync(Microsoft.CodeAnalysis.Solution solution, Microsoft.CodeAnalysis.ISymbol symbol, string newName, Microsoft.CodeAnalysis.Options.OptionSet optionSet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.AllowSimplificationToBaseType.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.AllowSimplificationToGenericType.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferAliasToQualification.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferImplicitTypeInference.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferImplicitTypeInLocalDeclaration.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.PreferOmittingModuleNamesInQualification.get -> Microsoft.CodeAnalysis.Options.Option<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyEventAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyFieldAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyMemberAccessWithThisOrMe.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyMethodAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.SimplificationOptions.QualifyPropertyAccess.get -> Microsoft.CodeAnalysis.Options.PerLanguageOption<bool>
static Microsoft.CodeAnalysis.Simplification.Simplifier.AddImportsAnnotation.get -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.Simplification.Simplifier.Annotation.get -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.Simplification.Simplifier.Expand(Microsoft.CodeAnalysis.SyntaxToken token, Microsoft.CodeAnalysis.SemanticModel semanticModel, Microsoft.CodeAnalysis.Workspace workspace, System.Func<Microsoft.CodeAnalysis.SyntaxNode, bool> expandInsideNode = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.SyntaxToken
static Microsoft.CodeAnalysis.Simplification.Simplifier.Expand<TNode>(TNode node, Microsoft.CodeAnalysis.SemanticModel semanticModel, Microsoft.CodeAnalysis.Workspace workspace, System.Func<Microsoft.CodeAnalysis.SyntaxNode, bool> expandInsideNode = null, bool expandParameter = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> TNode
static Microsoft.CodeAnalysis.Simplification.Simplifier.ExpandAsync(Microsoft.CodeAnalysis.SyntaxToken token, Microsoft.CodeAnalysis.Document document, System.Func<Microsoft.CodeAnalysis.SyntaxNode, bool> expandInsideNode = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SyntaxToken>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ExpandAsync<TNode>(TNode node, Microsoft.CodeAnalysis.Document document, System.Func<Microsoft.CodeAnalysis.SyntaxNode, bool> expandInsideNode = null, bool expandParameter = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<TNode>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.SyntaxAnnotation annotation, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document document, Microsoft.CodeAnalysis.Text.TextSpan span, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Simplification.Simplifier.ReduceAsync(Microsoft.CodeAnalysis.Document document, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Text.TextSpan> spans, Microsoft.CodeAnalysis.Options.OptionSet optionSet = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
static Microsoft.CodeAnalysis.Simplification.Simplifier.SpecialTypeAnnotation.get -> Microsoft.CodeAnalysis.SyntaxAnnotation
static Microsoft.CodeAnalysis.SolutionId.CreateFromSerialized(System.Guid id, string debugName = null) -> Microsoft.CodeAnalysis.SolutionId
static Microsoft.CodeAnalysis.SolutionId.CreateNewId(string debugName = null) -> Microsoft.CodeAnalysis.SolutionId
static Microsoft.CodeAnalysis.SolutionId.operator !=(Microsoft.CodeAnalysis.SolutionId left, Microsoft.CodeAnalysis.SolutionId right) -> bool
static Microsoft.CodeAnalysis.SolutionId.operator ==(Microsoft.CodeAnalysis.SolutionId left, Microsoft.CodeAnalysis.SolutionId right) -> bool
static Microsoft.CodeAnalysis.SolutionInfo.Create(Microsoft.CodeAnalysis.SolutionId id, Microsoft.CodeAnalysis.VersionStamp version, string filePath = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectInfo> projects = null, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference> analyzerReferences = null) -> Microsoft.CodeAnalysis.SolutionInfo
static Microsoft.CodeAnalysis.SolutionInfo.Create(Microsoft.CodeAnalysis.SolutionId id, Microsoft.CodeAnalysis.VersionStamp version, string filePath, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.ProjectInfo> projects) -> Microsoft.CodeAnalysis.SolutionInfo
static Microsoft.CodeAnalysis.TextAndVersion.Create(Microsoft.CodeAnalysis.Text.SourceText text, Microsoft.CodeAnalysis.VersionStamp version, string filePath = null) -> Microsoft.CodeAnalysis.TextAndVersion
static Microsoft.CodeAnalysis.TextLoader.From(Microsoft.CodeAnalysis.Text.SourceTextContainer container, Microsoft.CodeAnalysis.VersionStamp version, string filePath = null) -> Microsoft.CodeAnalysis.TextLoader
static Microsoft.CodeAnalysis.TextLoader.From(Microsoft.CodeAnalysis.TextAndVersion textAndVersion) -> Microsoft.CodeAnalysis.TextLoader
static Microsoft.CodeAnalysis.VersionStamp.Create() -> Microsoft.CodeAnalysis.VersionStamp
static Microsoft.CodeAnalysis.VersionStamp.Create(System.DateTime utcTimeLastModified) -> Microsoft.CodeAnalysis.VersionStamp
static Microsoft.CodeAnalysis.VersionStamp.Default.get -> Microsoft.CodeAnalysis.VersionStamp
static Microsoft.CodeAnalysis.VersionStamp.operator !=(Microsoft.CodeAnalysis.VersionStamp left, Microsoft.CodeAnalysis.VersionStamp right) -> bool
static Microsoft.CodeAnalysis.VersionStamp.operator ==(Microsoft.CodeAnalysis.VersionStamp left, Microsoft.CodeAnalysis.VersionStamp right) -> bool
static Microsoft.CodeAnalysis.Workspace.GetWorkspaceRegistration(Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer) -> Microsoft.CodeAnalysis.WorkspaceRegistration
static Microsoft.CodeAnalysis.Workspace.TryGetWorkspace(Microsoft.CodeAnalysis.Text.SourceTextContainer textContainer, out Microsoft.CodeAnalysis.Workspace workspace) -> bool
static Microsoft.CodeAnalysis.XmlDocumentationProvider.CreateFromBytes(byte[] xmlDocCommentBytes) -> Microsoft.CodeAnalysis.XmlDocumentationProvider
static Microsoft.CodeAnalysis.XmlDocumentationProvider.CreateFromFile(string xmlDocCommentFilePath) -> Microsoft.CodeAnalysis.XmlDocumentationProvider
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.QualifyEventAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.QualifyFieldAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.QualifyMethodAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.CodeStyleOptions.QualifyPropertyAccess -> Microsoft.CodeAnalysis.Options.PerLanguageOption<Microsoft.CodeAnalysis.CodeStyle.CodeStyleOption<bool>>
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Error -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.None -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Silent -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Suggestion -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
static readonly Microsoft.CodeAnalysis.CodeStyle.NotificationOption.Warning -> Microsoft.CodeAnalysis.CodeStyle.NotificationOption
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputePreviewOperationsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeActionOperation>>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.EquivalenceKey.get -> string
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedDocumentAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.PostProcessChangesAsync(Microsoft.CodeAnalysis.Document document, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Document>
virtual Microsoft.CodeAnalysis.CodeActions.CodeAction.Tags.get -> System.Collections.Immutable.ImmutableArray<string>
virtual Microsoft.CodeAnalysis.CodeActions.CodeActionOperation.Apply(Microsoft.CodeAnalysis.Workspace workspace, System.Threading.CancellationToken cancellationToken) -> void
virtual Microsoft.CodeAnalysis.CodeActions.CodeActionOperation.Title.get -> string
virtual Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider.GetFixAllProvider() -> Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
virtual Microsoft.CodeAnalysis.CodeFixes.FixAllProvider.GetSupportedFixAllDiagnosticIds(Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider originalCodeFixProvider) -> System.Collections.Generic.IEnumerable<string>
virtual Microsoft.CodeAnalysis.CodeFixes.FixAllProvider.GetSupportedFixAllScopes() -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.CodeFixes.FixAllScope>
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertNodesAfter(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> newDeclarations) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.InsertNodesBefore(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> newDeclarations) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.MemberAccessExpression(Microsoft.CodeAnalysis.SyntaxNode expression, Microsoft.CodeAnalysis.SyntaxNode memberName) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.OperatorDeclaration(Microsoft.CodeAnalysis.Editing.OperatorKind kind, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> parameters = null, Microsoft.CodeAnalysis.SyntaxNode returnType = null, Microsoft.CodeAnalysis.Accessibility accessibility = Microsoft.CodeAnalysis.Accessibility.NotApplicable, Microsoft.CodeAnalysis.Editing.DeclarationModifiers modifiers = default(Microsoft.CodeAnalysis.Editing.DeclarationModifiers), System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.SyntaxNode> statements = null) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveNode(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.RemoveNode(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxRemoveOptions options) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.Editing.SyntaxGenerator.ReplaceNode(Microsoft.CodeAnalysis.SyntaxNode root, Microsoft.CodeAnalysis.SyntaxNode node, Microsoft.CodeAnalysis.SyntaxNode newDeclaration) -> Microsoft.CodeAnalysis.SyntaxNode
virtual Microsoft.CodeAnalysis.FileTextLoader.CreateText(System.IO.Stream stream, Microsoft.CodeAnalysis.Workspace workspace) -> Microsoft.CodeAnalysis.Text.SourceText
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.GetLanguageServices(string languageName) -> Microsoft.CodeAnalysis.Host.HostLanguageServices
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.IsSupported(string languageName) -> bool
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.PersistentStorage.get -> Microsoft.CodeAnalysis.Host.IPersistentStorageService
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.SupportedLanguages.get -> System.Collections.Generic.IEnumerable<string>
virtual Microsoft.CodeAnalysis.Host.HostWorkspaceServices.TemporaryStorage.get -> Microsoft.CodeAnalysis.Host.ITemporaryStorageService
virtual Microsoft.CodeAnalysis.Workspace.AdjustReloadedProject(Microsoft.CodeAnalysis.Project oldProject, Microsoft.CodeAnalysis.Project reloadedProject) -> Microsoft.CodeAnalysis.Project
virtual Microsoft.CodeAnalysis.Workspace.AdjustReloadedSolution(Microsoft.CodeAnalysis.Solution oldSolution, Microsoft.CodeAnalysis.Solution reloadedSolution) -> Microsoft.CodeAnalysis.Solution
virtual Microsoft.CodeAnalysis.Workspace.ApplyAdditionalDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo info, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAdditionalDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAdditionalDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId id, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerConfigDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo info, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerConfigDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerConfigDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId id, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyAnalyzerReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference analyzerReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyCompilationOptionsChanged(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.CompilationOptions options) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyDocumentAdded(Microsoft.CodeAnalysis.DocumentInfo info, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyDocumentInfoChanged(Microsoft.CodeAnalysis.DocumentId id, Microsoft.CodeAnalysis.DocumentInfo info) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyDocumentRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyDocumentTextChanged(Microsoft.CodeAnalysis.DocumentId id, Microsoft.CodeAnalysis.Text.SourceText text) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyMetadataReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyMetadataReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.MetadataReference metadataReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyParseOptionsChanged(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ParseOptions options) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectAdded(Microsoft.CodeAnalysis.ProjectInfo project) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectChanges(Microsoft.CodeAnalysis.ProjectChanges projectChanges) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectReferenceAdded(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectReferenceRemoved(Microsoft.CodeAnalysis.ProjectId projectId, Microsoft.CodeAnalysis.ProjectReference projectReference) -> void
virtual Microsoft.CodeAnalysis.Workspace.ApplyProjectRemoved(Microsoft.CodeAnalysis.ProjectId projectId) -> void
virtual Microsoft.CodeAnalysis.Workspace.CanApplyChange(Microsoft.CodeAnalysis.ApplyChangesKind feature) -> bool
virtual Microsoft.CodeAnalysis.Workspace.CanApplyCompilationOptionChange(Microsoft.CodeAnalysis.CompilationOptions oldOptions, Microsoft.CodeAnalysis.CompilationOptions newOptions, Microsoft.CodeAnalysis.Project project) -> bool
virtual Microsoft.CodeAnalysis.Workspace.CanApplyParseOptionChange(Microsoft.CodeAnalysis.ParseOptions oldOptions, Microsoft.CodeAnalysis.ParseOptions newOptions, Microsoft.CodeAnalysis.Project project) -> bool
virtual Microsoft.CodeAnalysis.Workspace.CanOpenDocuments.get -> bool
virtual Microsoft.CodeAnalysis.Workspace.CheckDocumentCanBeRemoved(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.CheckProjectCanBeRemoved(Microsoft.CodeAnalysis.ProjectId projectId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ClearDocumentData(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ClearProjectData(Microsoft.CodeAnalysis.ProjectId projectId) -> void
virtual Microsoft.CodeAnalysis.Workspace.ClearSolutionData() -> void
virtual Microsoft.CodeAnalysis.Workspace.CloseAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.CloseAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.CloseDocument(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.Dispose(bool finalize) -> void
virtual Microsoft.CodeAnalysis.Workspace.GetAdditionalDocumentName(Microsoft.CodeAnalysis.DocumentId documentId) -> string
virtual Microsoft.CodeAnalysis.Workspace.GetAnalyzerConfigDocumentName(Microsoft.CodeAnalysis.DocumentId documentId) -> string
virtual Microsoft.CodeAnalysis.Workspace.GetDocumentIdInCurrentContext(Microsoft.CodeAnalysis.Text.SourceTextContainer container) -> Microsoft.CodeAnalysis.DocumentId
virtual Microsoft.CodeAnalysis.Workspace.GetDocumentName(Microsoft.CodeAnalysis.DocumentId documentId) -> string
virtual Microsoft.CodeAnalysis.Workspace.GetOpenDocumentIds(Microsoft.CodeAnalysis.ProjectId projectId = null) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
virtual Microsoft.CodeAnalysis.Workspace.GetProjectName(Microsoft.CodeAnalysis.ProjectId projectId) -> string
virtual Microsoft.CodeAnalysis.Workspace.GetRelatedDocumentIds(Microsoft.CodeAnalysis.Text.SourceTextContainer container) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.DocumentId>
virtual Microsoft.CodeAnalysis.Workspace.IsDocumentOpen(Microsoft.CodeAnalysis.DocumentId documentId) -> bool
virtual Microsoft.CodeAnalysis.Workspace.OnDocumentClosing(Microsoft.CodeAnalysis.DocumentId documentId) -> void
virtual Microsoft.CodeAnalysis.Workspace.OnDocumentTextChanged(Microsoft.CodeAnalysis.Document document) -> void
virtual Microsoft.CodeAnalysis.Workspace.OnProjectReloaded(Microsoft.CodeAnalysis.ProjectInfo reloadedProjectInfo) -> void
virtual Microsoft.CodeAnalysis.Workspace.OnProjectRemoved(Microsoft.CodeAnalysis.ProjectId projectId) -> void
virtual Microsoft.CodeAnalysis.Workspace.OnWorkspaceFailed(Microsoft.CodeAnalysis.WorkspaceDiagnostic diagnostic) -> void
virtual Microsoft.CodeAnalysis.Workspace.OpenAdditionalDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
virtual Microsoft.CodeAnalysis.Workspace.OpenAnalyzerConfigDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
virtual Microsoft.CodeAnalysis.Workspace.OpenDocument(Microsoft.CodeAnalysis.DocumentId documentId, bool activate = true) -> void
virtual Microsoft.CodeAnalysis.Workspace.PartialSemanticsEnabled.get -> bool
virtual Microsoft.CodeAnalysis.Workspace.TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution) -> bool
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Features/Core/Portable/Debugging/AbstractBreakpointResolver.NameAndArity.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Debugging
{
internal partial class AbstractBreakpointResolver
{
protected struct NameAndArity
{
public string Name;
public int Arity;
public NameAndArity(string name, int arity)
{
Name = name;
Arity = arity;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Debugging
{
internal partial class AbstractBreakpointResolver
{
protected struct NameAndArity
{
public string Name;
public int Arity;
public NameAndArity(string name, int arity)
{
Name = name;
Arity = arity;
}
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Workspaces/Core/Portable/Editing/OperatorKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Editing
{
public enum OperatorKind
{
/// <summary>
/// The name assigned to an implicit (widening) conversion.
/// </summary>
ImplicitConversion,
/// <summary>
/// The name assigned to an explicit (narrowing) conversion.
/// </summary>
ExplicitConversion,
/// <summary>
/// The name assigned to the Addition operator.
/// </summary>
Addition,
/// <summary>
/// The name assigned to the BitwiseAnd operator.
/// </summary>
BitwiseAnd,
/// <summary>
/// The name assigned to the BitwiseOr operator.
/// </summary>
BitwiseOr,
/// <summary>
/// The name assigned to the Decrement operator.
/// </summary>
Decrement,
/// <summary>
/// The name assigned to the Division operator.
/// </summary>
Division,
/// <summary>
/// The name assigned to the Equality operator.
/// </summary>
Equality,
/// <summary>
/// The name assigned to the ExclusiveOr operator.
/// </summary>
ExclusiveOr,
/// <summary>
/// The name assigned to the False operator.
/// </summary>
False,
/// <summary>
/// The name assigned to the GreaterThan operator.
/// </summary>
GreaterThan,
/// <summary>
/// The name assigned to the GreaterThanOrEqual operator.
/// </summary>
GreaterThanOrEqual,
/// <summary>
/// The name assigned to the Increment operator.
/// </summary>
Increment,
/// <summary>
/// The name assigned to the Inequality operator.
/// </summary>
Inequality,
/// <summary>
/// The name assigned to the LeftShift operator.
/// </summary>
LeftShift,
/// <summary>
/// The name assigned to the LessThan operator.
/// </summary>
LessThan,
/// <summary>
/// The name assigned to the LessThanOrEqual operator.
/// </summary>
LessThanOrEqual,
/// <summary>
/// The name assigned to the LogicalNot operator.
/// </summary>
LogicalNot,
/// <summary>
/// The name assigned to the Modulus operator.
/// </summary>
Modulus,
/// <summary>
/// The name assigned to the Multiply operator.
/// </summary>
Multiply,
/// <summary>
/// The name assigned to the OnesComplement operator.
/// </summary>
OnesComplement,
/// <summary>
/// The name assigned to the RightShift operator.
/// </summary>
RightShift,
/// <summary>
/// The name assigned to the Subtraction operator.
/// </summary>
Subtraction,
/// <summary>
/// The name assigned to the True operator.
/// </summary>
True,
/// <summary>
/// The name assigned to the UnaryNegation operator.
/// </summary>
UnaryNegation,
/// <summary>
/// The name assigned to the UnaryPlus operator.
/// </summary>
UnaryPlus,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Editing
{
public enum OperatorKind
{
/// <summary>
/// The name assigned to an implicit (widening) conversion.
/// </summary>
ImplicitConversion,
/// <summary>
/// The name assigned to an explicit (narrowing) conversion.
/// </summary>
ExplicitConversion,
/// <summary>
/// The name assigned to the Addition operator.
/// </summary>
Addition,
/// <summary>
/// The name assigned to the BitwiseAnd operator.
/// </summary>
BitwiseAnd,
/// <summary>
/// The name assigned to the BitwiseOr operator.
/// </summary>
BitwiseOr,
/// <summary>
/// The name assigned to the Decrement operator.
/// </summary>
Decrement,
/// <summary>
/// The name assigned to the Division operator.
/// </summary>
Division,
/// <summary>
/// The name assigned to the Equality operator.
/// </summary>
Equality,
/// <summary>
/// The name assigned to the ExclusiveOr operator.
/// </summary>
ExclusiveOr,
/// <summary>
/// The name assigned to the False operator.
/// </summary>
False,
/// <summary>
/// The name assigned to the GreaterThan operator.
/// </summary>
GreaterThan,
/// <summary>
/// The name assigned to the GreaterThanOrEqual operator.
/// </summary>
GreaterThanOrEqual,
/// <summary>
/// The name assigned to the Increment operator.
/// </summary>
Increment,
/// <summary>
/// The name assigned to the Inequality operator.
/// </summary>
Inequality,
/// <summary>
/// The name assigned to the LeftShift operator.
/// </summary>
LeftShift,
/// <summary>
/// The name assigned to the LessThan operator.
/// </summary>
LessThan,
/// <summary>
/// The name assigned to the LessThanOrEqual operator.
/// </summary>
LessThanOrEqual,
/// <summary>
/// The name assigned to the LogicalNot operator.
/// </summary>
LogicalNot,
/// <summary>
/// The name assigned to the Modulus operator.
/// </summary>
Modulus,
/// <summary>
/// The name assigned to the Multiply operator.
/// </summary>
Multiply,
/// <summary>
/// The name assigned to the OnesComplement operator.
/// </summary>
OnesComplement,
/// <summary>
/// The name assigned to the RightShift operator.
/// </summary>
RightShift,
/// <summary>
/// The name assigned to the Subtraction operator.
/// </summary>
Subtraction,
/// <summary>
/// The name assigned to the True operator.
/// </summary>
True,
/// <summary>
/// The name assigned to the UnaryNegation operator.
/// </summary>
UnaryNegation,
/// <summary>
/// The name assigned to the UnaryPlus operator.
/// </summary>
UnaryPlus,
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/MissingTypeReferences.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
//test
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE
{
public class MissingTypeReferences : CSharpTestBase
{
[Fact]
public void Test1()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.MDTestLib2);
TestMissingTypeReferencesHelper1(assembly);
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[]
{
TestReferences.SymbolsTests.MissingTypes.MDMissingType,
TestReferences.SymbolsTests.MissingTypes.MDMissingTypeLib,
TestMetadata.Net40.mscorlib
});
TestMissingTypeReferencesHelper2(assemblies);
}
private void TestMissingTypeReferencesHelper1(AssemblySymbol assembly)
{
var module0 = assembly.Modules[0];
var localTC10 = module0.GlobalNamespace.GetTypeMembers("TC10").Single();
MissingMetadataTypeSymbol @base = (MissingMetadataTypeSymbol)localTC10.BaseType();
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("Object", @base.Name);
Assert.Equal("System", @base.ContainingSymbol.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("System.Object[missing]", @base.ToTestDisplayString());
Assert.NotNull(@base.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.True(@base.ContainingAssembly.IsMissing);
Assert.Equal("mscorlib", @base.ContainingAssembly.Identity.Name);
var localTC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single();
var genericBase = (ErrorTypeSymbol)localTC8.BaseType();
Assert.Equal("C1<System.Type[missing]>[missing]", genericBase.ToTestDisplayString());
@base = (MissingMetadataTypeSymbol)genericBase.ConstructedFrom;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("C1", @base.Name);
Assert.Equal(1, @base.Arity);
Assert.Equal("C1<>[missing]", @base.ToTestDisplayString());
Assert.NotNull(@base.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.True(@base.ContainingAssembly.IsMissing);
Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name);
var localTC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single();
genericBase = (ErrorTypeSymbol)localTC7.BaseType();
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<TC7_T2>[missing]", genericBase.ToTestDisplayString());
Assert.True(genericBase.ContainingAssembly.IsMissing);
Assert.True(@base.ContainingAssembly.IsMissing);
Assert.Equal(@base.GetUseSiteDiagnostic().ToString(), genericBase.GetUseSiteDiagnostic().ToString());
Assert.Equal(@base.ErrorInfo.ToString(), genericBase.ErrorInfo.ToString());
var constructedFrom = genericBase.ConstructedFrom;
Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<>[missing]", constructedFrom.ToTestDisplayString());
Assert.Same(constructedFrom, constructedFrom.Construct(constructedFrom.TypeParameters.ToArray()));
Assert.Equal(genericBase, constructedFrom.Construct(genericBase.TypeArguments()));
genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol;
Assert.Equal("C1<TC7_T1>[missing].C3[missing]", genericBase.ToTestDisplayString());
Assert.Same(genericBase, genericBase.ConstructedFrom);
genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol;
Assert.Equal("C1<TC7_T1>[missing]", genericBase.ToTestDisplayString());
Assert.Same(genericBase.OriginalDefinition, genericBase.ConstructedFrom);
Assert.Equal("C1<>[missing]", genericBase.OriginalDefinition.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("C4", @base.Name);
Assert.Equal(1, @base.Arity);
Assert.Equal("C1<>[missing].C3[missing].C4<>[missing]", @base.ToTestDisplayString());
Assert.NotNull(@base.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name);
Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.Kind);
Assert.NotNull(@base.ContainingSymbol.ContainingAssembly);
Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingAssembly);
Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.ContainingSymbol.Kind);
Assert.NotNull(@base.ContainingSymbol.ContainingSymbol.ContainingAssembly);
Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingSymbol.ContainingAssembly);
}
private void TestMissingTypeReferencesHelper2(AssemblySymbol[] assemblies, bool reflectionOnly = false)
{
var module1 = assemblies[0].Modules[0];
var module2 = assemblies[1].Modules[0];
var assembly2 = (MetadataOrSourceAssemblySymbol)assemblies[1];
NamedTypeSymbol localTC = module1.GlobalNamespace.GetTypeMembers("TC1").Single();
var @base = (MissingMetadataTypeSymbol)localTC.BaseType();
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC1", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("MissingNS1.MissingC1[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.Equal("MissingNS1", @base.ContainingNamespace.Name);
Assert.Equal("", @base.ContainingNamespace.ContainingNamespace.Name);
Assert.NotNull(@base.ContainingSymbol);
Assert.NotNull(@base.ContainingAssembly);
localTC = module1.GlobalNamespace.GetTypeMembers("TC2").Single();
@base = (MissingMetadataTypeSymbol)localTC.BaseType();
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC2", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("MissingNS2.MissingNS3.MissingC2[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.Equal("MissingNS3", @base.ContainingNamespace.Name);
Assert.Equal("MissingNS2", @base.ContainingNamespace.ContainingNamespace.Name);
Assert.Equal("", @base.ContainingNamespace.ContainingNamespace.ContainingNamespace.Name);
Assert.NotNull(@base.ContainingSymbol);
Assert.NotNull(@base.ContainingAssembly);
localTC = module1.GlobalNamespace.GetTypeMembers("TC3").Single();
@base = (MissingMetadataTypeSymbol)localTC.BaseType();
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC3", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("NS4.MissingNS5.MissingC3[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.NotNull(@base.ContainingModule);
localTC = module1.GlobalNamespace.GetTypeMembers("TC4").Single();
var genericBase = localTC.BaseType();
Assert.Equal(SymbolKind.ErrorType, genericBase.Kind);
Assert.Equal("MissingC4<T1, S1>[missing]", genericBase.ToTestDisplayString());
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC4", @base.Name);
Assert.Equal(2, @base.Arity);
Assert.Equal("MissingC4<,>[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.NotNull(@base.ContainingModule);
var missingC4 = @base;
localTC = module1.GlobalNamespace.GetTypeMembers("TC5").Single();
genericBase = localTC.BaseType();
Assert.Equal("MissingC4<T1, S1>[missing].MissingC5<U1, V1, W1>[missing]", genericBase.ToTestDisplayString());
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC5", @base.Name);
Assert.Equal(3, @base.Arity);
Assert.Equal("MissingC4<,>[missing].MissingC5<,,>[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.True(@base.ContainingNamespace.IsGlobalNamespace);
Assert.Same(@base.ContainingSymbol, missingC4);
var localC6 = module2.GlobalNamespace.GetTypeMembers("C6").Single();
localTC = module1.GlobalNamespace.GetTypeMembers("TC6").Single();
genericBase = localTC.BaseType();
Assert.Equal("C6.MissingC7<U, V>[missing]", genericBase.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, genericBase.ContainingSymbol.Kind);
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC7", @base.Name);
Assert.Equal(2, @base.Arity);
Assert.Equal("C6.MissingC7<,>[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.Same(@base.ContainingSymbol, localC6);
Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace);
var missingC7 = @base;
localTC = module1.GlobalNamespace.GetTypeMembers("TC7").Single();
genericBase = localTC.BaseType();
Assert.Equal("C6.MissingC7<U, V>[missing].MissingC8[missing]", genericBase.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, genericBase.ContainingSymbol.Kind);
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC8", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("C6.MissingC7<,>[missing].MissingC8[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
if (!reflectionOnly)
{
Assert.Same(@base.ContainingSymbol, missingC7);
}
Assert.Equal(missingC7.ToTestDisplayString(), @base.ContainingSymbol.ToTestDisplayString());
Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace);
var missingC8 = @base;
localTC = module1.GlobalNamespace.GetTypeMembers("TC8").Single();
genericBase = localTC.BaseType();
Assert.Equal("C6.MissingC7<U, V>[missing].MissingC8[missing].MissingC9[missing]", genericBase.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, genericBase.ContainingSymbol.Kind);
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC9", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("C6.MissingC7<,>[missing].MissingC8[missing].MissingC9[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
if (!reflectionOnly)
{
Assert.Same(@base.ContainingSymbol, missingC8);
}
Assert.Equal(missingC8.ToTestDisplayString(), @base.ContainingSymbol.ToTestDisplayString());
Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace);
Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingNS1.MissingC1"));
Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingNS2.MissingNS3.MissingC2"));
Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("NS4.MissingNS5.MissingC3"));
Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingC4`2"));
}
[Fact]
public void Equality()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.MissingTypes.MissingTypesEquality1,
TestReferences.SymbolsTests.MissingTypes.MissingTypesEquality2,
TestReferences.SymbolsTests.MDTestLib1,
TestReferences.SymbolsTests.MDTestLib2
});
var asm1 = assemblies[0];
var asm1classC = asm1.GlobalNamespace.GetTypeMembers("C").Single();
var asm1m1 = asm1classC.GetMembers("M1").OfType<MethodSymbol>().Single();
var asm1m2 = asm1classC.GetMembers("M2").OfType<MethodSymbol>().Single();
var asm1m3 = asm1classC.GetMembers("M3").OfType<MethodSymbol>().Single();
var asm1m4 = asm1classC.GetMembers("M4").OfType<MethodSymbol>().Single();
var asm1m5 = asm1classC.GetMembers("M5").OfType<MethodSymbol>().Single();
var asm1m6 = asm1classC.GetMembers("M6").OfType<MethodSymbol>().Single();
var asm1m7 = asm1classC.GetMembers("M7").OfType<MethodSymbol>().Single();
var asm1m8 = asm1classC.GetMembers("M8").OfType<MethodSymbol>().Single();
Assert.NotEqual(asm1m2.ReturnType, asm1m1.ReturnType);
Assert.NotEqual(asm1m3.ReturnType, asm1m1.ReturnType);
Assert.NotEqual(asm1m4.ReturnType, asm1m1.ReturnType);
Assert.NotEqual(asm1m5.ReturnType, asm1m4.ReturnType);
Assert.NotEqual(asm1m6.ReturnType, asm1m4.ReturnType);
Assert.Equal(asm1m7.ReturnType, asm1m1.ReturnType);
Assert.Equal(asm1m8.ReturnType, asm1m4.ReturnType);
var asm2 = assemblies[1];
var asm2classC = asm2.GlobalNamespace.GetTypeMembers("C").Single();
var asm2m1 = asm2classC.GetMembers("M1").OfType<MethodSymbol>().Single();
var asm2m4 = asm2classC.GetMembers("M4").OfType<MethodSymbol>().Single();
Assert.Equal(asm2m1.ReturnType, asm1m1.ReturnType);
Assert.NotSame(asm1m4.ReturnType, asm2m4.ReturnType);
Assert.Equal(asm2m4.ReturnType, asm1m4.ReturnType);
Assert.Equal(asm1.GetSpecialType(SpecialType.System_Boolean), asm1.GetSpecialType(SpecialType.System_Boolean));
Assert.Equal(asm1.GetSpecialType(SpecialType.System_Boolean), asm2.GetSpecialType(SpecialType.System_Boolean));
MissingMetadataTypeSymbol[] missingTypes1 = new MissingMetadataTypeSymbol[15];
MissingMetadataTypeSymbol[] missingTypes2 = new MissingMetadataTypeSymbol[15];
var defaultName = new AssemblyIdentity("missing");
missingTypes1[0] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 0, true);
missingTypes1[1] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 1, true);
missingTypes1[2] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test2", 0, true);
missingTypes1[3] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 0, true);
missingTypes1[4] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 1, true);
missingTypes1[5] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test2", 0, true);
missingTypes1[6] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm2")).Modules[0], "", "test1", 0, true);
missingTypes1[7] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 0, true);
missingTypes1[8] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 1, true);
missingTypes1[9] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test2", 0, true);
missingTypes1[10] = new MissingMetadataTypeSymbol.TopLevel(asm2.Modules[0], "", "test1", 0, true);
missingTypes1[11] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 0, true);
missingTypes1[12] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 1, true);
missingTypes1[13] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test2", 0, true);
missingTypes1[14] = new MissingMetadataTypeSymbol.Nested(asm2classC, "test1", 0, true);
missingTypes2[0] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 0, true);
missingTypes2[1] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 1, true);
missingTypes2[2] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test2", 0, true);
missingTypes2[3] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 0, true);
missingTypes2[4] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 1, true);
missingTypes2[5] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test2", 0, true);
missingTypes2[6] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm2")).Modules[0], "", "test1", 0, true);
missingTypes2[7] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 0, true);
missingTypes2[8] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 1, true);
missingTypes2[9] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test2", 0, true);
missingTypes2[10] = new MissingMetadataTypeSymbol.TopLevel(asm2.Modules[0], "", "test1", 0, true);
missingTypes2[11] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 0, true);
missingTypes2[12] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 1, true);
missingTypes2[13] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test2", 0, true);
missingTypes2[14] = new MissingMetadataTypeSymbol.Nested(asm2classC, "test1", 0, true);
for (int i = 0; i < missingTypes1.Length; i++)
{
for (int j = 0; j < missingTypes2.Length; j++)
{
if (i == j)
{
Assert.Equal(missingTypes2[j], missingTypes1[i]);
Assert.Equal(missingTypes1[i], missingTypes2[j]);
}
else
{
Assert.NotEqual(missingTypes2[j], missingTypes1[i]);
Assert.NotEqual(missingTypes1[i], missingTypes2[j]);
}
}
}
var missingAssembly = new MissingAssemblySymbol(new AssemblyIdentity("asm1"));
Assert.True(missingAssembly.Equals(missingAssembly));
Assert.NotEqual(new object(), missingAssembly);
Assert.False(missingAssembly.Equals(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.Linq;
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;
//test
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE
{
public class MissingTypeReferences : CSharpTestBase
{
[Fact]
public void Test1()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.MDTestLib2);
TestMissingTypeReferencesHelper1(assembly);
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[]
{
TestReferences.SymbolsTests.MissingTypes.MDMissingType,
TestReferences.SymbolsTests.MissingTypes.MDMissingTypeLib,
TestMetadata.Net40.mscorlib
});
TestMissingTypeReferencesHelper2(assemblies);
}
private void TestMissingTypeReferencesHelper1(AssemblySymbol assembly)
{
var module0 = assembly.Modules[0];
var localTC10 = module0.GlobalNamespace.GetTypeMembers("TC10").Single();
MissingMetadataTypeSymbol @base = (MissingMetadataTypeSymbol)localTC10.BaseType();
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("Object", @base.Name);
Assert.Equal("System", @base.ContainingSymbol.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("System.Object[missing]", @base.ToTestDisplayString());
Assert.NotNull(@base.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.True(@base.ContainingAssembly.IsMissing);
Assert.Equal("mscorlib", @base.ContainingAssembly.Identity.Name);
var localTC8 = module0.GlobalNamespace.GetTypeMembers("TC8").Single();
var genericBase = (ErrorTypeSymbol)localTC8.BaseType();
Assert.Equal("C1<System.Type[missing]>[missing]", genericBase.ToTestDisplayString());
@base = (MissingMetadataTypeSymbol)genericBase.ConstructedFrom;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("C1", @base.Name);
Assert.Equal(1, @base.Arity);
Assert.Equal("C1<>[missing]", @base.ToTestDisplayString());
Assert.NotNull(@base.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.True(@base.ContainingAssembly.IsMissing);
Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name);
var localTC7 = module0.GlobalNamespace.GetTypeMembers("TC7").Single();
genericBase = (ErrorTypeSymbol)localTC7.BaseType();
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<TC7_T2>[missing]", genericBase.ToTestDisplayString());
Assert.True(genericBase.ContainingAssembly.IsMissing);
Assert.True(@base.ContainingAssembly.IsMissing);
Assert.Equal(@base.GetUseSiteDiagnostic().ToString(), genericBase.GetUseSiteDiagnostic().ToString());
Assert.Equal(@base.ErrorInfo.ToString(), genericBase.ErrorInfo.ToString());
var constructedFrom = genericBase.ConstructedFrom;
Assert.Equal("C1<TC7_T1>[missing].C3[missing].C4<>[missing]", constructedFrom.ToTestDisplayString());
Assert.Same(constructedFrom, constructedFrom.Construct(constructedFrom.TypeParameters.ToArray()));
Assert.Equal(genericBase, constructedFrom.Construct(genericBase.TypeArguments()));
genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol;
Assert.Equal("C1<TC7_T1>[missing].C3[missing]", genericBase.ToTestDisplayString());
Assert.Same(genericBase, genericBase.ConstructedFrom);
genericBase = (ErrorTypeSymbol)genericBase.ContainingSymbol;
Assert.Equal("C1<TC7_T1>[missing]", genericBase.ToTestDisplayString());
Assert.Same(genericBase.OriginalDefinition, genericBase.ConstructedFrom);
Assert.Equal("C1<>[missing]", genericBase.OriginalDefinition.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("C4", @base.Name);
Assert.Equal(1, @base.Arity);
Assert.Equal("C1<>[missing].C3[missing].C4<>[missing]", @base.ToTestDisplayString());
Assert.NotNull(@base.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.Equal("MDTestLib1", @base.ContainingAssembly.Identity.Name);
Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.Kind);
Assert.NotNull(@base.ContainingSymbol.ContainingAssembly);
Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingAssembly);
Assert.Equal(SymbolKind.ErrorType, @base.ContainingSymbol.ContainingSymbol.Kind);
Assert.NotNull(@base.ContainingSymbol.ContainingSymbol.ContainingAssembly);
Assert.Same(@base.ContainingAssembly, @base.ContainingSymbol.ContainingSymbol.ContainingAssembly);
}
private void TestMissingTypeReferencesHelper2(AssemblySymbol[] assemblies, bool reflectionOnly = false)
{
var module1 = assemblies[0].Modules[0];
var module2 = assemblies[1].Modules[0];
var assembly2 = (MetadataOrSourceAssemblySymbol)assemblies[1];
NamedTypeSymbol localTC = module1.GlobalNamespace.GetTypeMembers("TC1").Single();
var @base = (MissingMetadataTypeSymbol)localTC.BaseType();
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC1", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("MissingNS1.MissingC1[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.Equal("MissingNS1", @base.ContainingNamespace.Name);
Assert.Equal("", @base.ContainingNamespace.ContainingNamespace.Name);
Assert.NotNull(@base.ContainingSymbol);
Assert.NotNull(@base.ContainingAssembly);
localTC = module1.GlobalNamespace.GetTypeMembers("TC2").Single();
@base = (MissingMetadataTypeSymbol)localTC.BaseType();
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC2", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("MissingNS2.MissingNS3.MissingC2[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.Equal("MissingNS3", @base.ContainingNamespace.Name);
Assert.Equal("MissingNS2", @base.ContainingNamespace.ContainingNamespace.Name);
Assert.Equal("", @base.ContainingNamespace.ContainingNamespace.ContainingNamespace.Name);
Assert.NotNull(@base.ContainingSymbol);
Assert.NotNull(@base.ContainingAssembly);
localTC = module1.GlobalNamespace.GetTypeMembers("TC3").Single();
@base = (MissingMetadataTypeSymbol)localTC.BaseType();
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC3", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("NS4.MissingNS5.MissingC3[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.NotNull(@base.ContainingModule);
localTC = module1.GlobalNamespace.GetTypeMembers("TC4").Single();
var genericBase = localTC.BaseType();
Assert.Equal(SymbolKind.ErrorType, genericBase.Kind);
Assert.Equal("MissingC4<T1, S1>[missing]", genericBase.ToTestDisplayString());
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC4", @base.Name);
Assert.Equal(2, @base.Arity);
Assert.Equal("MissingC4<,>[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.NotNull(@base.ContainingNamespace);
Assert.NotNull(@base.ContainingSymbol);
Assert.NotNull(@base.ContainingModule);
var missingC4 = @base;
localTC = module1.GlobalNamespace.GetTypeMembers("TC5").Single();
genericBase = localTC.BaseType();
Assert.Equal("MissingC4<T1, S1>[missing].MissingC5<U1, V1, W1>[missing]", genericBase.ToTestDisplayString());
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC5", @base.Name);
Assert.Equal(3, @base.Arity);
Assert.Equal("MissingC4<,>[missing].MissingC5<,,>[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.True(@base.ContainingNamespace.IsGlobalNamespace);
Assert.Same(@base.ContainingSymbol, missingC4);
var localC6 = module2.GlobalNamespace.GetTypeMembers("C6").Single();
localTC = module1.GlobalNamespace.GetTypeMembers("TC6").Single();
genericBase = localTC.BaseType();
Assert.Equal("C6.MissingC7<U, V>[missing]", genericBase.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, genericBase.ContainingSymbol.Kind);
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC7", @base.Name);
Assert.Equal(2, @base.Arity);
Assert.Equal("C6.MissingC7<,>[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
Assert.Same(@base.ContainingSymbol, localC6);
Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace);
var missingC7 = @base;
localTC = module1.GlobalNamespace.GetTypeMembers("TC7").Single();
genericBase = localTC.BaseType();
Assert.Equal("C6.MissingC7<U, V>[missing].MissingC8[missing]", genericBase.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, genericBase.ContainingSymbol.Kind);
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC8", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("C6.MissingC7<,>[missing].MissingC8[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
if (!reflectionOnly)
{
Assert.Same(@base.ContainingSymbol, missingC7);
}
Assert.Equal(missingC7.ToTestDisplayString(), @base.ContainingSymbol.ToTestDisplayString());
Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace);
var missingC8 = @base;
localTC = module1.GlobalNamespace.GetTypeMembers("TC8").Single();
genericBase = localTC.BaseType();
Assert.Equal("C6.MissingC7<U, V>[missing].MissingC8[missing].MissingC9[missing]", genericBase.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, genericBase.ContainingSymbol.Kind);
@base = (MissingMetadataTypeSymbol)genericBase.OriginalDefinition;
Assert.Equal(SymbolKind.ErrorType, @base.Kind);
Assert.False(@base.IsNamespace);
Assert.True(@base.IsType);
Assert.Equal("MissingC9", @base.Name);
Assert.Equal(0, @base.Arity);
Assert.Equal("C6.MissingC7<,>[missing].MissingC8[missing].MissingC9[missing]", @base.ToTestDisplayString());
Assert.Same(@base.ContainingAssembly, module2.ContainingAssembly);
if (!reflectionOnly)
{
Assert.Same(@base.ContainingSymbol, missingC8);
}
Assert.Equal(missingC8.ToTestDisplayString(), @base.ContainingSymbol.ToTestDisplayString());
Assert.Same(@base.ContainingNamespace, localC6.ContainingNamespace);
Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingNS1.MissingC1"));
Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingNS2.MissingNS3.MissingC2"));
Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("NS4.MissingNS5.MissingC3"));
Assert.IsAssignableFrom<MissingMetadataTypeSymbol>(assembly2.CachedTypeByEmittedName("MissingC4`2"));
}
[Fact]
public void Equality()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[]
{
TestReferences.SymbolsTests.MissingTypes.MissingTypesEquality1,
TestReferences.SymbolsTests.MissingTypes.MissingTypesEquality2,
TestReferences.SymbolsTests.MDTestLib1,
TestReferences.SymbolsTests.MDTestLib2
});
var asm1 = assemblies[0];
var asm1classC = asm1.GlobalNamespace.GetTypeMembers("C").Single();
var asm1m1 = asm1classC.GetMembers("M1").OfType<MethodSymbol>().Single();
var asm1m2 = asm1classC.GetMembers("M2").OfType<MethodSymbol>().Single();
var asm1m3 = asm1classC.GetMembers("M3").OfType<MethodSymbol>().Single();
var asm1m4 = asm1classC.GetMembers("M4").OfType<MethodSymbol>().Single();
var asm1m5 = asm1classC.GetMembers("M5").OfType<MethodSymbol>().Single();
var asm1m6 = asm1classC.GetMembers("M6").OfType<MethodSymbol>().Single();
var asm1m7 = asm1classC.GetMembers("M7").OfType<MethodSymbol>().Single();
var asm1m8 = asm1classC.GetMembers("M8").OfType<MethodSymbol>().Single();
Assert.NotEqual(asm1m2.ReturnType, asm1m1.ReturnType);
Assert.NotEqual(asm1m3.ReturnType, asm1m1.ReturnType);
Assert.NotEqual(asm1m4.ReturnType, asm1m1.ReturnType);
Assert.NotEqual(asm1m5.ReturnType, asm1m4.ReturnType);
Assert.NotEqual(asm1m6.ReturnType, asm1m4.ReturnType);
Assert.Equal(asm1m7.ReturnType, asm1m1.ReturnType);
Assert.Equal(asm1m8.ReturnType, asm1m4.ReturnType);
var asm2 = assemblies[1];
var asm2classC = asm2.GlobalNamespace.GetTypeMembers("C").Single();
var asm2m1 = asm2classC.GetMembers("M1").OfType<MethodSymbol>().Single();
var asm2m4 = asm2classC.GetMembers("M4").OfType<MethodSymbol>().Single();
Assert.Equal(asm2m1.ReturnType, asm1m1.ReturnType);
Assert.NotSame(asm1m4.ReturnType, asm2m4.ReturnType);
Assert.Equal(asm2m4.ReturnType, asm1m4.ReturnType);
Assert.Equal(asm1.GetSpecialType(SpecialType.System_Boolean), asm1.GetSpecialType(SpecialType.System_Boolean));
Assert.Equal(asm1.GetSpecialType(SpecialType.System_Boolean), asm2.GetSpecialType(SpecialType.System_Boolean));
MissingMetadataTypeSymbol[] missingTypes1 = new MissingMetadataTypeSymbol[15];
MissingMetadataTypeSymbol[] missingTypes2 = new MissingMetadataTypeSymbol[15];
var defaultName = new AssemblyIdentity("missing");
missingTypes1[0] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 0, true);
missingTypes1[1] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 1, true);
missingTypes1[2] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test2", 0, true);
missingTypes1[3] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 0, true);
missingTypes1[4] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 1, true);
missingTypes1[5] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test2", 0, true);
missingTypes1[6] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm2")).Modules[0], "", "test1", 0, true);
missingTypes1[7] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 0, true);
missingTypes1[8] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 1, true);
missingTypes1[9] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test2", 0, true);
missingTypes1[10] = new MissingMetadataTypeSymbol.TopLevel(asm2.Modules[0], "", "test1", 0, true);
missingTypes1[11] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 0, true);
missingTypes1[12] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 1, true);
missingTypes1[13] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test2", 0, true);
missingTypes1[14] = new MissingMetadataTypeSymbol.Nested(asm2classC, "test1", 0, true);
missingTypes2[0] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 0, true);
missingTypes2[1] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test1", 1, true);
missingTypes2[2] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(defaultName).Modules[0], "", "test2", 0, true);
missingTypes2[3] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 0, true);
missingTypes2[4] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test1", 1, true);
missingTypes2[5] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm1")).Modules[0], "", "test2", 0, true);
missingTypes2[6] = new MissingMetadataTypeSymbol.TopLevel(new MissingAssemblySymbol(new AssemblyIdentity("asm2")).Modules[0], "", "test1", 0, true);
missingTypes2[7] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 0, true);
missingTypes2[8] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test1", 1, true);
missingTypes2[9] = new MissingMetadataTypeSymbol.TopLevel(asm1.Modules[0], "", "test2", 0, true);
missingTypes2[10] = new MissingMetadataTypeSymbol.TopLevel(asm2.Modules[0], "", "test1", 0, true);
missingTypes2[11] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 0, true);
missingTypes2[12] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test1", 1, true);
missingTypes2[13] = new MissingMetadataTypeSymbol.Nested(asm1classC, "test2", 0, true);
missingTypes2[14] = new MissingMetadataTypeSymbol.Nested(asm2classC, "test1", 0, true);
for (int i = 0; i < missingTypes1.Length; i++)
{
for (int j = 0; j < missingTypes2.Length; j++)
{
if (i == j)
{
Assert.Equal(missingTypes2[j], missingTypes1[i]);
Assert.Equal(missingTypes1[i], missingTypes2[j]);
}
else
{
Assert.NotEqual(missingTypes2[j], missingTypes1[i]);
Assert.NotEqual(missingTypes1[i], missingTypes2[j]);
}
}
}
var missingAssembly = new MissingAssemblySymbol(new AssemblyIdentity("asm1"));
Assert.True(missingAssembly.Equals(missingAssembly));
Assert.NotEqual(new object(), missingAssembly);
Assert.False(missingAssembly.Equals(null));
}
}
}
| -1 |
dotnet/roslyn | 56,488 | Make abstract type actually implement interface. | Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | CyrusNajmabadi | "2021-09-17T18:55:33Z" | "2021-09-18T00:30:26Z" | 69e33ded29a49279b3da616fb73a3e4e445f3546 | fb5150d1c427f20030d315b9b42ce084dd8eb486 | Make abstract type actually implement interface.. Not sure why this abstract class wasn't implenting the interface it claimed to. This made life difficult as it meant that hte abstract type couldn't refer to extensions on the interface it was supposed to be implementing. | ./src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetInfoService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
/// <summary>
/// This service is created on the UI thread during package initialization, but it must not
/// block the initialization process.
/// </summary>
internal abstract class AbstractSnippetInfoService : ForegroundThreadAffinitizedObject, ISnippetInfoService, IVsExpansionEvents
{
private readonly Guid _languageGuidForSnippets;
private IVsExpansionManager? _expansionManager;
/// <summary>
/// Initialize these to empty values. When returning from <see cref="GetSnippetsIfAvailable "/>
/// and <see cref="SnippetShortcutExists_NonBlocking"/>, we return the current set of known
/// snippets rather than waiting for initial results.
/// </summary>
protected ImmutableArray<SnippetInfo> snippets = ImmutableArray.Create<SnippetInfo>();
protected IImmutableSet<string> snippetShortcuts = ImmutableHashSet.Create<string>();
// Guard the snippets and snippetShortcut fields so that returned result sets are always
// complete.
protected object cacheGuard = new();
private readonly IAsynchronousOperationListener _waiter;
private readonly IThreadingContext _threadingContext;
public AbstractSnippetInfoService(
IThreadingContext threadingContext,
Shell.IAsyncServiceProvider serviceProvider,
Guid languageGuidForSnippets,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext)
{
_waiter = listenerProvider.GetListener(FeatureAttribute.Snippets);
_languageGuidForSnippets = languageGuidForSnippets;
_threadingContext = threadingContext;
_threadingContext.RunWithShutdownBlockAsync((_) => InitializeAndPopulateSnippetsCacheAsync(serviceProvider));
}
private async Task InitializeAndPopulateSnippetsCacheAsync(Shell.IAsyncServiceProvider asyncServiceProvider)
{
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();
var textManager = (IVsTextManager2?)await asyncServiceProvider.GetServiceAsync(typeof(SVsTextManager)).ConfigureAwait(true);
Assumes.Present(textManager);
if (textManager.GetExpansionManager(out _expansionManager) == VSConstants.S_OK)
{
ComEventSink.Advise<IVsExpansionEvents>(_expansionManager, this);
await PopulateSnippetCacheAsync().ConfigureAwait(false);
}
}
public int OnAfterSnippetsUpdate()
{
AssertIsForeground();
if (_expansionManager != null)
{
_threadingContext.RunWithShutdownBlockAsync((_) => PopulateSnippetCacheAsync());
}
return VSConstants.S_OK;
}
public int OnAfterSnippetsKeyBindingChange([ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")] uint dwCmdGuid, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")] uint dwCmdId, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")] int fBound)
=> VSConstants.S_OK;
public IEnumerable<SnippetInfo> GetSnippetsIfAvailable()
{
// Immediately return the known set of snippets, even if we're still in the process
// of calculating a more up-to-date list.
lock (cacheGuard)
{
return snippets;
}
}
public bool SnippetShortcutExists_NonBlocking(string shortcut)
{
if (shortcut == null)
{
return false;
}
// Check against the known set of snippets, even if we're still in the process of
// calculating a more up-to-date list.
lock (cacheGuard)
{
return snippetShortcuts.Contains(shortcut);
}
}
public virtual bool ShouldFormatSnippet(SnippetInfo snippetInfo)
=> false;
private async Task PopulateSnippetCacheAsync()
{
using var token = _waiter.BeginAsyncOperation(GetType().Name + ".Start");
RoslynDebug.Assert(_expansionManager != null);
// In Dev14 Update2+ the platform always provides an IExpansion Manager
var expansionManager = (IExpansionManager)_expansionManager;
// Call the asynchronous IExpansionManager API from a background thread
await TaskScheduler.Default;
var expansionEnumerator = await expansionManager.EnumerateExpansionsAsync(
_languageGuidForSnippets,
0, // shortCutOnly
Array.Empty<string>(), // types
0, // countTypes
1, // includeNULLTypes
1 // includeDulicates: Allows snippets with the same title but different shortcuts
).ConfigureAwait(false);
// The rest of the process requires being on the UI thread, see the explanation on
// PopulateSnippetCacheFromExpansionEnumeration for details
await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();
PopulateSnippetCacheFromExpansionEnumeration(expansionEnumerator);
}
/// <remarks>
/// This method must be called on the UI thread because it eventually calls into
/// IVsExpansionEnumeration.Next, which must be called on the UI thread due to an issue
/// with how the call is marshalled.
///
/// The second parameter for IVsExpansionEnumeration.Next is defined like this:
/// [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.VsExpansion")] IntPtr[] rgelt
///
/// We pass a pointer for rgelt that we expect to be populated as the result. This
/// eventually calls into the native CExpansionEnumeratorShim::Next method, which has the
/// same contract of expecting a non-null rgelt that it can drop expansion data into. When
/// we call from the UI thread, this transition from managed code to the
/// CExpansionEnumeratorShim goes smoothly and everything works.
///
/// When we call from a background thread, the COM marshaller has to move execution to the
/// UI thread, and as part of this process it uses the interface as defined in the idl to
/// set up the appropriate arguments to pass. The same parameter from the idl is defined as
/// [out, size_is(celt), length_is(*pceltFetched)] VsExpansion **rgelt
///
/// Because rgelt is specified as an <c>out</c> parameter, the marshaller is discarding the
/// pointer we passed and substituting the null reference. This then causes a null
/// reference exception in the shim. Calling from the UI thread avoids this marshaller.
/// </remarks>
private void PopulateSnippetCacheFromExpansionEnumeration(IVsExpansionEnumeration expansionEnumerator)
{
AssertIsForeground();
var updatedSnippets = ExtractSnippetInfo(expansionEnumerator);
var updatedSnippetShortcuts = GetShortcutsHashFromSnippets(updatedSnippets);
lock (cacheGuard)
{
snippets = updatedSnippets;
snippetShortcuts = updatedSnippetShortcuts;
}
}
private ImmutableArray<SnippetInfo> ExtractSnippetInfo(IVsExpansionEnumeration expansionEnumerator)
{
AssertIsForeground();
var snippetListBuilder = ImmutableArray.CreateBuilder<SnippetInfo>();
var snippetInfo = new VsExpansion();
var pSnippetInfo = new IntPtr[1];
try
{
// Allocate enough memory for one VSExpansion structure. This memory is filled in by the Next method.
pSnippetInfo[0] = Marshal.AllocCoTaskMem(Marshal.SizeOf(snippetInfo));
expansionEnumerator.GetCount(out var count);
for (uint i = 0; i < count; i++)
{
expansionEnumerator.Next(1, pSnippetInfo, out var fetched);
if (fetched > 0)
{
// Convert the returned blob of data into a structure that can be read in managed code.
snippetInfo = ConvertToVsExpansionAndFree(pSnippetInfo[0]);
if (!string.IsNullOrEmpty(snippetInfo.shortcut))
{
snippetListBuilder.Add(new SnippetInfo(snippetInfo.shortcut, snippetInfo.title, snippetInfo.description, snippetInfo.path));
}
}
}
}
finally
{
Marshal.FreeCoTaskMem(pSnippetInfo[0]);
}
return snippetListBuilder.ToImmutable();
}
protected static IImmutableSet<string> GetShortcutsHashFromSnippets(ImmutableArray<SnippetInfo> updatedSnippets)
{
return new HashSet<string>(updatedSnippets.Select(s => s.Shortcut), StringComparer.OrdinalIgnoreCase)
.ToImmutableHashSet(StringComparer.OrdinalIgnoreCase);
}
private static VsExpansion ConvertToVsExpansionAndFree(IntPtr expansionPtr)
{
var buffer = (VsExpansionWithIntPtrs)Marshal.PtrToStructure(expansionPtr, typeof(VsExpansionWithIntPtrs));
var expansion = new VsExpansion();
ConvertToStringAndFree(ref buffer.DescriptionPtr, ref expansion.description);
ConvertToStringAndFree(ref buffer.PathPtr, ref expansion.path);
ConvertToStringAndFree(ref buffer.ShortcutPtr, ref expansion.shortcut);
ConvertToStringAndFree(ref buffer.TitlePtr, ref expansion.title);
return expansion;
}
private static void ConvertToStringAndFree(ref IntPtr ptr, ref string? str)
{
if (ptr != IntPtr.Zero)
{
str = Marshal.PtrToStringBSTR(ptr);
Marshal.FreeBSTR(ptr);
ptr = IntPtr.Zero;
}
}
/// <summary>
/// This structure is used to facilitate the interop calls with IVsExpansionEnumeration.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct VsExpansionWithIntPtrs
{
public IntPtr PathPtr;
public IntPtr TitlePtr;
public IntPtr ShortcutPtr;
public IntPtr DescriptionPtr;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
/// <summary>
/// This service is created on the UI thread during package initialization, but it must not
/// block the initialization process.
/// </summary>
internal abstract class AbstractSnippetInfoService : ForegroundThreadAffinitizedObject, ISnippetInfoService, IVsExpansionEvents
{
private readonly Guid _languageGuidForSnippets;
private IVsExpansionManager? _expansionManager;
/// <summary>
/// Initialize these to empty values. When returning from <see cref="GetSnippetsIfAvailable "/>
/// and <see cref="SnippetShortcutExists_NonBlocking"/>, we return the current set of known
/// snippets rather than waiting for initial results.
/// </summary>
protected ImmutableArray<SnippetInfo> snippets = ImmutableArray.Create<SnippetInfo>();
protected IImmutableSet<string> snippetShortcuts = ImmutableHashSet.Create<string>();
// Guard the snippets and snippetShortcut fields so that returned result sets are always
// complete.
protected object cacheGuard = new();
private readonly IAsynchronousOperationListener _waiter;
private readonly IThreadingContext _threadingContext;
public AbstractSnippetInfoService(
IThreadingContext threadingContext,
Shell.IAsyncServiceProvider serviceProvider,
Guid languageGuidForSnippets,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext)
{
_waiter = listenerProvider.GetListener(FeatureAttribute.Snippets);
_languageGuidForSnippets = languageGuidForSnippets;
_threadingContext = threadingContext;
_threadingContext.RunWithShutdownBlockAsync((_) => InitializeAndPopulateSnippetsCacheAsync(serviceProvider));
}
private async Task InitializeAndPopulateSnippetsCacheAsync(Shell.IAsyncServiceProvider asyncServiceProvider)
{
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();
var textManager = (IVsTextManager2?)await asyncServiceProvider.GetServiceAsync(typeof(SVsTextManager)).ConfigureAwait(true);
Assumes.Present(textManager);
if (textManager.GetExpansionManager(out _expansionManager) == VSConstants.S_OK)
{
ComEventSink.Advise<IVsExpansionEvents>(_expansionManager, this);
await PopulateSnippetCacheAsync().ConfigureAwait(false);
}
}
public int OnAfterSnippetsUpdate()
{
AssertIsForeground();
if (_expansionManager != null)
{
_threadingContext.RunWithShutdownBlockAsync((_) => PopulateSnippetCacheAsync());
}
return VSConstants.S_OK;
}
public int OnAfterSnippetsKeyBindingChange([ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")] uint dwCmdGuid, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")] uint dwCmdId, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")] int fBound)
=> VSConstants.S_OK;
public IEnumerable<SnippetInfo> GetSnippetsIfAvailable()
{
// Immediately return the known set of snippets, even if we're still in the process
// of calculating a more up-to-date list.
lock (cacheGuard)
{
return snippets;
}
}
public bool SnippetShortcutExists_NonBlocking(string shortcut)
{
if (shortcut == null)
{
return false;
}
// Check against the known set of snippets, even if we're still in the process of
// calculating a more up-to-date list.
lock (cacheGuard)
{
return snippetShortcuts.Contains(shortcut);
}
}
public virtual bool ShouldFormatSnippet(SnippetInfo snippetInfo)
=> false;
private async Task PopulateSnippetCacheAsync()
{
using var token = _waiter.BeginAsyncOperation(GetType().Name + ".Start");
RoslynDebug.Assert(_expansionManager != null);
// In Dev14 Update2+ the platform always provides an IExpansion Manager
var expansionManager = (IExpansionManager)_expansionManager;
// Call the asynchronous IExpansionManager API from a background thread
await TaskScheduler.Default;
var expansionEnumerator = await expansionManager.EnumerateExpansionsAsync(
_languageGuidForSnippets,
0, // shortCutOnly
Array.Empty<string>(), // types
0, // countTypes
1, // includeNULLTypes
1 // includeDulicates: Allows snippets with the same title but different shortcuts
).ConfigureAwait(false);
// The rest of the process requires being on the UI thread, see the explanation on
// PopulateSnippetCacheFromExpansionEnumeration for details
await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();
PopulateSnippetCacheFromExpansionEnumeration(expansionEnumerator);
}
/// <remarks>
/// This method must be called on the UI thread because it eventually calls into
/// IVsExpansionEnumeration.Next, which must be called on the UI thread due to an issue
/// with how the call is marshalled.
///
/// The second parameter for IVsExpansionEnumeration.Next is defined like this:
/// [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.VsExpansion")] IntPtr[] rgelt
///
/// We pass a pointer for rgelt that we expect to be populated as the result. This
/// eventually calls into the native CExpansionEnumeratorShim::Next method, which has the
/// same contract of expecting a non-null rgelt that it can drop expansion data into. When
/// we call from the UI thread, this transition from managed code to the
/// CExpansionEnumeratorShim goes smoothly and everything works.
///
/// When we call from a background thread, the COM marshaller has to move execution to the
/// UI thread, and as part of this process it uses the interface as defined in the idl to
/// set up the appropriate arguments to pass. The same parameter from the idl is defined as
/// [out, size_is(celt), length_is(*pceltFetched)] VsExpansion **rgelt
///
/// Because rgelt is specified as an <c>out</c> parameter, the marshaller is discarding the
/// pointer we passed and substituting the null reference. This then causes a null
/// reference exception in the shim. Calling from the UI thread avoids this marshaller.
/// </remarks>
private void PopulateSnippetCacheFromExpansionEnumeration(IVsExpansionEnumeration expansionEnumerator)
{
AssertIsForeground();
var updatedSnippets = ExtractSnippetInfo(expansionEnumerator);
var updatedSnippetShortcuts = GetShortcutsHashFromSnippets(updatedSnippets);
lock (cacheGuard)
{
snippets = updatedSnippets;
snippetShortcuts = updatedSnippetShortcuts;
}
}
private ImmutableArray<SnippetInfo> ExtractSnippetInfo(IVsExpansionEnumeration expansionEnumerator)
{
AssertIsForeground();
var snippetListBuilder = ImmutableArray.CreateBuilder<SnippetInfo>();
var snippetInfo = new VsExpansion();
var pSnippetInfo = new IntPtr[1];
try
{
// Allocate enough memory for one VSExpansion structure. This memory is filled in by the Next method.
pSnippetInfo[0] = Marshal.AllocCoTaskMem(Marshal.SizeOf(snippetInfo));
expansionEnumerator.GetCount(out var count);
for (uint i = 0; i < count; i++)
{
expansionEnumerator.Next(1, pSnippetInfo, out var fetched);
if (fetched > 0)
{
// Convert the returned blob of data into a structure that can be read in managed code.
snippetInfo = ConvertToVsExpansionAndFree(pSnippetInfo[0]);
if (!string.IsNullOrEmpty(snippetInfo.shortcut))
{
snippetListBuilder.Add(new SnippetInfo(snippetInfo.shortcut, snippetInfo.title, snippetInfo.description, snippetInfo.path));
}
}
}
}
finally
{
Marshal.FreeCoTaskMem(pSnippetInfo[0]);
}
return snippetListBuilder.ToImmutable();
}
protected static IImmutableSet<string> GetShortcutsHashFromSnippets(ImmutableArray<SnippetInfo> updatedSnippets)
{
return new HashSet<string>(updatedSnippets.Select(s => s.Shortcut), StringComparer.OrdinalIgnoreCase)
.ToImmutableHashSet(StringComparer.OrdinalIgnoreCase);
}
private static VsExpansion ConvertToVsExpansionAndFree(IntPtr expansionPtr)
{
var buffer = (VsExpansionWithIntPtrs)Marshal.PtrToStructure(expansionPtr, typeof(VsExpansionWithIntPtrs));
var expansion = new VsExpansion();
ConvertToStringAndFree(ref buffer.DescriptionPtr, ref expansion.description);
ConvertToStringAndFree(ref buffer.PathPtr, ref expansion.path);
ConvertToStringAndFree(ref buffer.ShortcutPtr, ref expansion.shortcut);
ConvertToStringAndFree(ref buffer.TitlePtr, ref expansion.title);
return expansion;
}
private static void ConvertToStringAndFree(ref IntPtr ptr, ref string? str)
{
if (ptr != IntPtr.Zero)
{
str = Marshal.PtrToStringBSTR(ptr);
Marshal.FreeBSTR(ptr);
ptr = IntPtr.Zero;
}
}
/// <summary>
/// This structure is used to facilitate the interop calls with IVsExpansionEnumeration.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct VsExpansionWithIntPtrs
{
public IntPtr PathPtr;
public IntPtr TitlePtr;
public IntPtr ShortcutPtr;
public IntPtr DescriptionPtr;
}
}
}
| -1 |
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/EditorFeatures/Core/Implementation/InlineRename/AbstractEditorInlineRenameService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractEditorInlineRenameService : IEditorInlineRenameService
{
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
protected AbstractEditorInlineRenameService(IEnumerable<IRefactorNotifyService> refactorNotifyServices)
=> _refactorNotifyServices = refactorNotifyServices;
public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken)
{
var triggerToken = await GetTriggerTokenAsync(document, position, cancellationToken).ConfigureAwait(false);
if (triggerToken == default)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_must_rename_an_identifier);
}
return await GetRenameInfoAsync(_refactorNotifyServices, document, triggerToken, cancellationToken).ConfigureAwait(false);
}
internal static async Task<IInlineRenameInfo> GetRenameInfoAsync(
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
Document document, SyntaxToken triggerToken, CancellationToken cancellationToken)
{
var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>();
if (syntaxFactsService.IsReservedOrContextualKeyword(triggerToken))
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_must_rename_an_identifier);
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var tokenRenameInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, triggerToken, cancellationToken);
// Rename was invoked on a member group reference in a nameof expression.
// Trigger the rename on any of the candidate symbols but force the
// RenameOverloads option to be on.
var triggerSymbol = tokenRenameInfo.HasSymbols ? tokenRenameInfo.Symbols.First() : null;
if (triggerSymbol == null)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
// see https://github.com/dotnet/roslyn/issues/10898
// we are disabling rename for tuple fields for now
// 1) compiler does not return correct location information in these symbols
// 2) renaming tuple fields seems a complex enough thing to require some design
if (triggerSymbol.ContainingType?.IsTupleType == true)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
// If rename is invoked on a member group reference in a nameof expression, then the
// RenameOverloads option should be forced on.
var forceRenameOverloads = tokenRenameInfo.IsMemberGroup;
if (syntaxFactsService.IsTypeNamedVarInVariableOrFieldDeclaration(triggerToken, triggerToken.Parent))
{
// To check if var in this context is a real type, or the keyword, we need to
// speculatively bind the identifier "var". If it returns a symbol, it's a real type,
// if not, it's the keyword.
// see bugs 659683 (compiler API) and 659705 (rename/workspace api) for examples
var symbolForVar = semanticModel.GetSpeculativeSymbolInfo(
triggerToken.SpanStart,
triggerToken.Parent!,
SpeculativeBindingOption.BindAsTypeOrNamespace).Symbol;
if (symbolForVar == null)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
}
var symbol = await RenameLocations.ReferenceProcessing.TryGetRenamableSymbolAsync(document, triggerToken.SpanStart, cancellationToken: cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
if (symbol.Kind == SymbolKind.Alias && symbol.IsExtern)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
// Cannot rename constructors in VB. TODO: this logic should be in the VB subclass of this type.
var workspace = document.Project.Solution.Workspace;
if (symbol.Kind == SymbolKind.NamedType &&
symbol.Language == LanguageNames.VisualBasic &&
triggerToken.ToString().Equals("New", StringComparison.OrdinalIgnoreCase))
{
var originalSymbol = await SymbolFinder.FindSymbolAtPositionAsync(
semanticModel, triggerToken.SpanStart, workspace, cancellationToken: cancellationToken).ConfigureAwait(false);
if (originalSymbol != null && originalSymbol.IsConstructor())
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
}
if (syntaxFactsService.IsTypeNamedDynamic(triggerToken, triggerToken.Parent))
{
if (symbol.Kind == SymbolKind.DynamicType)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
}
// we allow implicit locals and parameters of Event handlers
if (symbol.IsImplicitlyDeclared &&
symbol.Kind != SymbolKind.Local &&
!(symbol.Kind == SymbolKind.Parameter &&
symbol.ContainingSymbol.Kind == SymbolKind.Method &&
symbol.ContainingType != null &&
symbol.ContainingType.IsDelegateType() &&
symbol.ContainingType.AssociatedSymbol != null))
{
// We enable the parameter in RaiseEvent, if the Event is declared with a signature. If the Event is declared as a
// delegate type, we do not have a connection between the delegate type and the event.
// this prevents a rename in this case :(.
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
if (symbol.Kind == SymbolKind.Property && symbol.ContainingType.IsAnonymousType)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.Renaming_anonymous_type_members_is_not_yet_supported);
}
if (symbol.IsErrorType())
{
return new FailureInlineRenameInfo(EditorFeaturesResources.Please_resolve_errors_in_your_code_before_renaming_this_element);
}
if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.UserDefinedOperator)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_operators);
}
var symbolLocations = symbol.Locations;
// Does our symbol exist in an unchangeable location?
var documentSpans = ArrayBuilder<DocumentSpan>.GetInstance();
foreach (var location in symbolLocations)
{
if (location.IsInMetadata)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_elements_that_are_defined_in_metadata);
}
else if (location.IsInSource)
{
var solution = document.Project.Solution;
var sourceDocument = solution.GetRequiredDocument(location.SourceTree);
if (sourceDocument is SourceGeneratedDocument)
{
// The file is generated so we can't go editing it (for now)
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
if (document.Project.IsSubmission)
{
var projectIdOfLocation = sourceDocument.Project.Id;
if (solution.Projects.Any(p => p.IsSubmission && p.ProjectReferences.Any(r => r.ProjectId == projectIdOfLocation)))
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_elements_from_previous_submissions);
}
}
else
{
// We eventually need to return the symbol locations, so we must convert each location to a DocumentSpan since our return type is language-agnostic.
documentSpans.Add(new DocumentSpan(sourceDocument, location.SourceSpan));
}
}
else
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
}
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var triggerText = sourceText.ToString(triggerToken.Span);
return new SymbolInlineRenameInfo(
refactorNotifyServices, document, triggerToken.Span, triggerText,
symbol, forceRenameOverloads, documentSpans.ToImmutableAndFree(), cancellationToken);
}
private static async Task<SyntaxToken> GetTriggerTokenAsync(Document document, int position, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var token = await syntaxTree.GetTouchingWordAsync(position, syntaxFacts, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
return token;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractEditorInlineRenameService : IEditorInlineRenameService
{
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
protected AbstractEditorInlineRenameService(IEnumerable<IRefactorNotifyService> refactorNotifyServices)
=> _refactorNotifyServices = refactorNotifyServices;
protected abstract bool CheckLanguageSpecificIssues(
SemanticModel semantic, ISymbol symbol, SyntaxToken triggerToken, [NotNullWhen(true)] out string? langError);
public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken)
{
var triggerToken = await GetTriggerTokenAsync(document, position, cancellationToken).ConfigureAwait(false);
if (triggerToken == default)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_must_rename_an_identifier);
}
return await GetRenameInfoAsync(_refactorNotifyServices, document, triggerToken, cancellationToken).ConfigureAwait(false);
}
private async Task<IInlineRenameInfo> GetRenameInfoAsync(
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
Document document, SyntaxToken triggerToken, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
if (syntaxFacts.IsReservedOrContextualKeyword(triggerToken))
return new FailureInlineRenameInfo(EditorFeaturesResources.You_must_rename_an_identifier);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var tokenRenameInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, triggerToken, cancellationToken);
// Rename was invoked on a member group reference in a nameof expression.
// Trigger the rename on any of the candidate symbols but force the
// RenameOverloads option to be on.
var triggerSymbol = tokenRenameInfo.HasSymbols ? tokenRenameInfo.Symbols.First() : null;
if (triggerSymbol == null)
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
// see https://github.com/dotnet/roslyn/issues/10898
// we are disabling rename for tuple fields for now
// 1) compiler does not return correct location information in these symbols
// 2) renaming tuple fields seems a complex enough thing to require some design
if (triggerSymbol.ContainingType?.IsTupleType == true)
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
// If rename is invoked on a member group reference in a nameof expression, then the
// RenameOverloads option should be forced on.
var forceRenameOverloads = tokenRenameInfo.IsMemberGroup;
var symbol = await RenameLocations.ReferenceProcessing.TryGetRenamableSymbolAsync(document, triggerToken.SpanStart, cancellationToken: cancellationToken).ConfigureAwait(false);
if (symbol == null)
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
if (symbol.Kind == SymbolKind.Alias && symbol.IsExtern)
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
// Cannot rename constructors in VB. TODO: this logic should be in the VB subclass of this type.
var workspace = document.Project.Solution.Workspace;
if (symbol.Kind == SymbolKind.NamedType &&
symbol.Language == LanguageNames.VisualBasic &&
triggerToken.ToString().Equals("New", StringComparison.OrdinalIgnoreCase))
{
var originalSymbol = await SymbolFinder.FindSymbolAtPositionAsync(
semanticModel, triggerToken.SpanStart, workspace, cancellationToken: cancellationToken).ConfigureAwait(false);
if (originalSymbol != null && originalSymbol.IsConstructor())
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
if (CheckLanguageSpecificIssues(semanticModel, symbol, triggerToken, out var langError))
return new FailureInlineRenameInfo(langError);
// we allow implicit locals and parameters of Event handlers
if (symbol.IsImplicitlyDeclared &&
symbol.Kind != SymbolKind.Local &&
!(symbol.Kind == SymbolKind.Parameter &&
symbol.ContainingSymbol.Kind == SymbolKind.Method &&
symbol.ContainingType != null &&
symbol.ContainingType.IsDelegateType() &&
symbol.ContainingType.AssociatedSymbol != null))
{
// We enable the parameter in RaiseEvent, if the Event is declared with a signature. If the Event is declared as a
// delegate type, we do not have a connection between the delegate type and the event.
// this prevents a rename in this case :(.
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
if (symbol.Kind == SymbolKind.Property && symbol.ContainingType.IsAnonymousType)
return new FailureInlineRenameInfo(EditorFeaturesResources.Renaming_anonymous_type_members_is_not_yet_supported);
if (symbol.IsErrorType())
return new FailureInlineRenameInfo(EditorFeaturesResources.Please_resolve_errors_in_your_code_before_renaming_this_element);
if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.UserDefinedOperator)
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_operators);
var symbolLocations = symbol.Locations;
// Does our symbol exist in an unchangeable location?
var documentSpans = ArrayBuilder<DocumentSpan>.GetInstance();
foreach (var location in symbolLocations)
{
if (location.IsInMetadata)
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_elements_that_are_defined_in_metadata);
}
else if (location.IsInSource)
{
var solution = document.Project.Solution;
var sourceDocument = solution.GetRequiredDocument(location.SourceTree);
if (sourceDocument is SourceGeneratedDocument)
{
// The file is generated so we can't go editing it (for now)
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
if (document.Project.IsSubmission)
{
var projectIdOfLocation = sourceDocument.Project.Id;
if (solution.Projects.Any(p => p.IsSubmission && p.ProjectReferences.Any(r => r.ProjectId == projectIdOfLocation)))
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_elements_from_previous_submissions);
}
else
{
// We eventually need to return the symbol locations, so we must convert each location to a DocumentSpan since our return type is language-agnostic.
documentSpans.Add(new DocumentSpan(sourceDocument, location.SourceSpan));
}
}
else
{
return new FailureInlineRenameInfo(EditorFeaturesResources.You_cannot_rename_this_element);
}
}
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var triggerText = sourceText.ToString(triggerToken.Span);
return new SymbolInlineRenameInfo(
refactorNotifyServices, document, triggerToken.Span, triggerText,
symbol, forceRenameOverloads, documentSpans.ToImmutableAndFree(), cancellationToken);
}
private static async Task<SyntaxToken> GetTriggerTokenAsync(Document document, int position, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var token = await syntaxTree.GetTouchingWordAsync(position, syntaxFacts, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
return token;
}
}
}
| 1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/VisualStudio/CSharp/Impl/LanguageService/CSharpHelpContextService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.F1Help;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExportLanguageService(typeof(IHelpContextService), LanguageNames.CSharp), Shared]
internal class CSharpHelpContextService : AbstractHelpContextService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpHelpContextService()
{
}
public override string Language
{
get
{
return "csharp";
}
}
public override string Product
{
get
{
return "csharp";
}
}
private static string Keyword(string text)
=> text + "_CSharpKeyword";
public override async Task<string> GetHelpTermAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
// For now, find the token under the start of the selection.
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = await syntaxTree.GetTouchingTokenAsync(span.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
if (IsValid(token, span))
{
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(span, cancellationToken).ConfigureAwait(false);
var result = TryGetText(token, semanticModel, document, syntaxFacts, cancellationToken);
if (string.IsNullOrEmpty(result))
{
var previousToken = token.GetPreviousToken();
if (IsValid(previousToken, span))
{
result = TryGetText(previousToken, semanticModel, document, syntaxFacts, cancellationToken);
}
}
return result;
}
var trivia = root.FindTrivia(span.Start, findInsideTrivia: true);
if (trivia.Span.IntersectsWith(span) && trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia &&
trivia.Token.GetAncestor<RegionDirectiveTriviaSyntax>() != null)
{
return "#region";
}
if (trivia.IsRegularOrDocComment())
{
// just find the first "word" that intersects with our position
var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
var start = span.Start;
var end = span.Start;
while (start > 0 && syntaxFacts.IsIdentifierPartCharacter(text[start - 1]))
{
start--;
}
while (end < text.Length - 1 && syntaxFacts.IsIdentifierPartCharacter(text[end]))
{
end++;
}
return text.GetSubText(TextSpan.FromBounds(start, end)).ToString();
}
return string.Empty;
}
private static bool IsValid(SyntaxToken token, TextSpan span)
{
// If the token doesn't actually intersect with our position, give up
return token.Kind() == SyntaxKind.EndIfDirectiveTrivia || token.Span.IntersectsWith(span);
}
private string TryGetText(SyntaxToken token, SemanticModel semanticModel, Document document, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
if (TryGetTextForSpecialCharacters(token, out var text) ||
TryGetTextForContextualKeyword(token, out text) ||
TryGetTextForCombinationKeyword(token, syntaxFacts, out text) ||
TryGetTextForKeyword(token, syntaxFacts, out text) ||
TryGetTextForPreProcessor(token, syntaxFacts, out text) ||
TryGetTextForOperator(token, document, out text) ||
TryGetTextForSymbol(token, semanticModel, document, cancellationToken, out text))
{
return text;
}
return string.Empty;
}
private bool TryGetTextForSpecialCharacters(SyntaxToken token, out string text)
{
if (token.IsKind(SyntaxKind.InterpolatedStringStartToken) ||
token.IsKind(SyntaxKind.InterpolatedStringEndToken) ||
token.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
text = "$_CSharpKeyword";
return true;
}
if (token.IsVerbatimStringLiteral())
{
text = "@_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken))
{
text = "@$_CSharpKeyword";
return true;
}
text = null;
return false;
}
private bool TryGetTextForSymbol(SyntaxToken token, SemanticModel semanticModel, Document document, CancellationToken cancellationToken, out string text)
{
ISymbol symbol;
if (token.Parent is TypeArgumentListSyntax)
{
var genericName = token.GetAncestor<GenericNameSyntax>();
symbol = semanticModel.GetSymbolInfo(genericName, cancellationToken).Symbol ?? semanticModel.GetTypeInfo(genericName, cancellationToken).Type;
}
else if (token.Parent is NullableTypeSyntax && token.IsKind(SyntaxKind.QuestionToken))
{
text = "System.Nullable`1";
return true;
}
else
{
symbol = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken)
.GetAnySymbol(includeType: true);
if (symbol == null)
{
var bindableParent = document.GetLanguageService<ISyntaxFactsService>().TryGetBindableParent(token);
var overloads = bindableParent != null ? semanticModel.GetMemberGroup(bindableParent) : ImmutableArray<ISymbol>.Empty;
symbol = overloads.FirstOrDefault();
}
}
// Local: return the name if it's the declaration, otherwise the type
if (symbol is ILocalSymbol localSymbol && !symbol.DeclaringSyntaxReferences.Any(d => d.GetSyntax().DescendantTokens().Contains(token)))
{
symbol = localSymbol.Type;
}
// Range variable: use the type
if (symbol is IRangeVariableSymbol)
{
var info = semanticModel.GetTypeInfo(token.Parent, cancellationToken);
symbol = info.Type;
}
// Just use syntaxfacts for operators
if (symbol is IMethodSymbol method && method.MethodKind == MethodKind.BuiltinOperator)
{
text = null;
return false;
}
text = symbol != null ? FormatSymbol(symbol) : null;
return symbol != null;
}
private static bool TryGetTextForOperator(SyntaxToken token, Document document, out string text)
{
if (token.IsKind(SyntaxKind.ExclamationToken) &&
token.Parent.IsKind(SyntaxKind.SuppressNullableWarningExpression))
{
text = Keyword("nullForgiving");
return true;
}
// Workaround IsPredefinedOperator returning true for '<' in generics.
if (token is { RawKind: (int)SyntaxKind.LessThanToken, Parent: not BinaryExpressionSyntax })
{
text = null;
return false;
}
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
if (syntaxFacts.IsOperator(token) || syntaxFacts.IsPredefinedOperator(token) || SyntaxFacts.IsAssignmentExpressionOperatorToken(token.Kind()))
{
text = Keyword(syntaxFacts.GetText(token.RawKind));
return true;
}
if (token.IsKind(SyntaxKind.ColonColonToken))
{
text = "::_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.ColonToken) && token.Parent is NameColonSyntax)
{
text = "namedParameter_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.QuestionToken) && token.Parent is ConditionalExpressionSyntax)
{
text = "?_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.EqualsGreaterThanToken))
{
text = "=>_CSharpKeyword";
return true;
}
text = null;
return false;
}
private static bool TryGetTextForPreProcessor(SyntaxToken token, ISyntaxFactsService syntaxFacts, out string text)
{
if (syntaxFacts.IsPreprocessorKeyword(token))
{
text = "#" + token.Text;
return true;
}
if (token.IsKind(SyntaxKind.EndOfDirectiveToken) && token.GetAncestor<RegionDirectiveTriviaSyntax>() != null)
{
text = "#region";
return true;
}
text = null;
return false;
}
private static bool TryGetTextForContextualKeyword(SyntaxToken token, out string text)
{
if (token.Text == "nameof")
{
text = Keyword("nameof");
return true;
}
if (token.IsContextualKeyword())
{
switch (token.Kind())
{
case SyntaxKind.PartialKeyword:
if (token.Parent.GetAncestorOrThis<MethodDeclarationSyntax>() != null)
{
text = "partialmethod_CSharpKeyword";
return true;
}
else if (token.Parent.GetAncestorOrThis<TypeDeclarationSyntax>() != null)
{
text = "partialtype_CSharpKeyword";
return true;
}
break;
case SyntaxKind.WhereKeyword:
if (token.Parent.GetAncestorOrThis<TypeParameterConstraintClauseSyntax>() != null)
{
text = "whereconstraint_CSharpKeyword";
}
else
{
text = "whereclause_CSharpKeyword";
}
return true;
}
}
text = null;
return false;
}
private static bool TryGetTextForCombinationKeyword(SyntaxToken token, ISyntaxFactsService syntaxFacts, out string text)
{
switch (token.Kind())
{
case SyntaxKind.PrivateKeyword when ModifiersContains(token, syntaxFacts, SyntaxKind.ProtectedKeyword):
case SyntaxKind.ProtectedKeyword when ModifiersContains(token, syntaxFacts, SyntaxKind.PrivateKeyword):
text = "privateprotected_CSharpKeyword";
return true;
case SyntaxKind.ProtectedKeyword when ModifiersContains(token, syntaxFacts, SyntaxKind.InternalKeyword):
case SyntaxKind.InternalKeyword when ModifiersContains(token, syntaxFacts, SyntaxKind.ProtectedKeyword):
text = "protectedinternal_CSharpKeyword";
return true;
case SyntaxKind.UsingKeyword when token.Parent is UsingDirectiveSyntax:
text = token.GetNextToken().IsKind(SyntaxKind.StaticKeyword)
? "using-static_CSharpKeyword"
: "using_CSharpKeyword";
return true;
case SyntaxKind.StaticKeyword when token.Parent is UsingDirectiveSyntax:
text = "using-static_CSharpKeyword";
return true;
}
text = null;
return false;
static bool ModifiersContains(SyntaxToken token, ISyntaxFactsService syntaxFacts, SyntaxKind kind)
{
return syntaxFacts.GetModifiers(token.Parent).Any(t => t.IsKind(kind));
}
}
private static bool TryGetTextForKeyword(SyntaxToken token, ISyntaxFactsService syntaxFacts, out string text)
{
if (token.IsKind(SyntaxKind.InKeyword))
{
if (token.GetAncestor<FromClauseSyntax>() != null)
{
text = "from_CSharpKeyword";
return true;
}
if (token.GetAncestor<JoinClauseSyntax>() != null)
{
text = "join_CSharpKeyword";
return true;
}
}
if (token.IsKind(SyntaxKind.DefaultKeyword) && token.Parent is DefaultSwitchLabelSyntax)
{
text = Keyword("defaultcase");
return true;
}
if (token.IsKind(SyntaxKind.ClassKeyword) && token.Parent is ClassOrStructConstraintSyntax)
{
text = Keyword("classconstraint");
return true;
}
if (token.IsKind(SyntaxKind.StructKeyword) && token.Parent is ClassOrStructConstraintSyntax)
{
text = Keyword("structconstraint");
return true;
}
if (token.IsKind(SyntaxKind.UsingKeyword) && token.Parent is UsingStatementSyntax or LocalDeclarationStatementSyntax)
{
text = Keyword("using-statement");
return true;
}
if (token.IsKeyword())
{
text = Keyword(token.Text);
return true;
}
if (token.ValueText == "var" && token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.Parent is VariableDeclarationSyntax declaration && token.Parent == declaration.Type)
{
text = "var_CSharpKeyword";
return true;
}
if (syntaxFacts.IsTypeNamedDynamic(token, token.Parent))
{
text = "dynamic_CSharpKeyword";
return true;
}
text = null;
return false;
}
private static string FormatNamespaceOrTypeSymbol(INamespaceOrTypeSymbol symbol)
{
var displayString = symbol.ToDisplayString(TypeFormat);
if (symbol is ITypeSymbol type && type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
return "System.Nullable`1";
}
if (symbol.GetTypeArguments().Any())
{
return $"{displayString}`{symbol.GetTypeArguments().Length}";
}
return displayString;
}
public override string FormatSymbol(ISymbol symbol)
{
if (symbol is ITypeSymbol || symbol is INamespaceSymbol)
{
return FormatNamespaceOrTypeSymbol((INamespaceOrTypeSymbol)symbol);
}
if (symbol.MatchesKind(SymbolKind.Alias, SymbolKind.Local, SymbolKind.Parameter))
{
return FormatSymbol(symbol.GetSymbolType());
}
var containingType = FormatNamespaceOrTypeSymbol(symbol.ContainingType);
var name = symbol.ToDisplayString(NameFormat);
if (symbol.IsConstructor())
{
return $"{containingType}.#ctor";
}
if (symbol.GetTypeArguments().Any())
{
return $"{containingType}.{name}``{symbol.GetTypeArguments().Length}";
}
return $"{containingType}.{name}";
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.F1Help;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExportLanguageService(typeof(IHelpContextService), LanguageNames.CSharp), Shared]
internal class CSharpHelpContextService : AbstractHelpContextService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpHelpContextService()
{
}
public override string Language
{
get
{
return "csharp";
}
}
public override string Product
{
get
{
return "csharp";
}
}
private static string Keyword(string text)
=> text + "_CSharpKeyword";
public override async Task<string> GetHelpTermAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
// For now, find the token under the start of the selection.
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = await syntaxTree.GetTouchingTokenAsync(span.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
if (IsValid(token, span))
{
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(span, cancellationToken).ConfigureAwait(false);
var result = TryGetText(token, semanticModel, document, syntaxFacts, cancellationToken);
if (string.IsNullOrEmpty(result))
{
var previousToken = token.GetPreviousToken();
if (IsValid(previousToken, span))
{
result = TryGetText(previousToken, semanticModel, document, syntaxFacts, cancellationToken);
}
}
return result;
}
var trivia = root.FindTrivia(span.Start, findInsideTrivia: true);
if (trivia.Span.IntersectsWith(span) && trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia &&
trivia.Token.GetAncestor<RegionDirectiveTriviaSyntax>() != null)
{
return "#region";
}
if (trivia.IsRegularOrDocComment())
{
// just find the first "word" that intersects with our position
var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
var start = span.Start;
var end = span.Start;
while (start > 0 && syntaxFacts.IsIdentifierPartCharacter(text[start - 1]))
{
start--;
}
while (end < text.Length - 1 && syntaxFacts.IsIdentifierPartCharacter(text[end]))
{
end++;
}
return text.GetSubText(TextSpan.FromBounds(start, end)).ToString();
}
return string.Empty;
}
private static bool IsValid(SyntaxToken token, TextSpan span)
{
// If the token doesn't actually intersect with our position, give up
return token.Kind() == SyntaxKind.EndIfDirectiveTrivia || token.Span.IntersectsWith(span);
}
private string TryGetText(SyntaxToken token, SemanticModel semanticModel, Document document, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
if (TryGetTextForSpecialCharacters(token, out var text) ||
TryGetTextForContextualKeyword(token, out text) ||
TryGetTextForCombinationKeyword(token, syntaxFacts, out text) ||
TryGetTextForKeyword(token, out text) ||
TryGetTextForPreProcessor(token, syntaxFacts, out text) ||
TryGetTextForOperator(token, document, out text) ||
TryGetTextForSymbol(token, semanticModel, document, cancellationToken, out text))
{
return text;
}
return string.Empty;
}
private bool TryGetTextForSpecialCharacters(SyntaxToken token, out string text)
{
if (token.IsKind(SyntaxKind.InterpolatedStringStartToken) ||
token.IsKind(SyntaxKind.InterpolatedStringEndToken) ||
token.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
text = "$_CSharpKeyword";
return true;
}
if (token.IsVerbatimStringLiteral())
{
text = "@_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken))
{
text = "@$_CSharpKeyword";
return true;
}
text = null;
return false;
}
private bool TryGetTextForSymbol(SyntaxToken token, SemanticModel semanticModel, Document document, CancellationToken cancellationToken, out string text)
{
ISymbol symbol;
if (token.Parent is TypeArgumentListSyntax)
{
var genericName = token.GetAncestor<GenericNameSyntax>();
symbol = semanticModel.GetSymbolInfo(genericName, cancellationToken).Symbol ?? semanticModel.GetTypeInfo(genericName, cancellationToken).Type;
}
else if (token.Parent is NullableTypeSyntax && token.IsKind(SyntaxKind.QuestionToken))
{
text = "System.Nullable`1";
return true;
}
else
{
symbol = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken)
.GetAnySymbol(includeType: true);
if (symbol == null)
{
var bindableParent = document.GetLanguageService<ISyntaxFactsService>().TryGetBindableParent(token);
var overloads = bindableParent != null ? semanticModel.GetMemberGroup(bindableParent) : ImmutableArray<ISymbol>.Empty;
symbol = overloads.FirstOrDefault();
}
}
// Local: return the name if it's the declaration, otherwise the type
if (symbol is ILocalSymbol localSymbol && !symbol.DeclaringSyntaxReferences.Any(d => d.GetSyntax().DescendantTokens().Contains(token)))
{
symbol = localSymbol.Type;
}
// Range variable: use the type
if (symbol is IRangeVariableSymbol)
{
var info = semanticModel.GetTypeInfo(token.Parent, cancellationToken);
symbol = info.Type;
}
// Just use syntaxfacts for operators
if (symbol is IMethodSymbol method && method.MethodKind == MethodKind.BuiltinOperator)
{
text = null;
return false;
}
text = symbol != null ? FormatSymbol(symbol) : null;
return symbol != null;
}
private static bool TryGetTextForOperator(SyntaxToken token, Document document, out string text)
{
if (token.IsKind(SyntaxKind.ExclamationToken) &&
token.Parent.IsKind(SyntaxKind.SuppressNullableWarningExpression))
{
text = Keyword("nullForgiving");
return true;
}
// Workaround IsPredefinedOperator returning true for '<' in generics.
if (token is { RawKind: (int)SyntaxKind.LessThanToken, Parent: not BinaryExpressionSyntax })
{
text = null;
return false;
}
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
if (syntaxFacts.IsOperator(token) || syntaxFacts.IsPredefinedOperator(token) || SyntaxFacts.IsAssignmentExpressionOperatorToken(token.Kind()))
{
text = Keyword(syntaxFacts.GetText(token.RawKind));
return true;
}
if (token.IsKind(SyntaxKind.ColonColonToken))
{
text = "::_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.ColonToken) && token.Parent is NameColonSyntax)
{
text = "namedParameter_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.QuestionToken) && token.Parent is ConditionalExpressionSyntax)
{
text = "?_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.EqualsGreaterThanToken))
{
text = "=>_CSharpKeyword";
return true;
}
text = null;
return false;
}
private static bool TryGetTextForPreProcessor(SyntaxToken token, ISyntaxFactsService syntaxFacts, out string text)
{
if (syntaxFacts.IsPreprocessorKeyword(token))
{
text = "#" + token.Text;
return true;
}
if (token.IsKind(SyntaxKind.EndOfDirectiveToken) && token.GetAncestor<RegionDirectiveTriviaSyntax>() != null)
{
text = "#region";
return true;
}
text = null;
return false;
}
private static bool TryGetTextForContextualKeyword(SyntaxToken token, out string text)
{
if (token.Text == "nameof")
{
text = Keyword("nameof");
return true;
}
if (token.IsContextualKeyword())
{
switch (token.Kind())
{
case SyntaxKind.PartialKeyword:
if (token.Parent.GetAncestorOrThis<MethodDeclarationSyntax>() != null)
{
text = "partialmethod_CSharpKeyword";
return true;
}
else if (token.Parent.GetAncestorOrThis<TypeDeclarationSyntax>() != null)
{
text = "partialtype_CSharpKeyword";
return true;
}
break;
case SyntaxKind.WhereKeyword:
if (token.Parent.GetAncestorOrThis<TypeParameterConstraintClauseSyntax>() != null)
{
text = "whereconstraint_CSharpKeyword";
}
else
{
text = "whereclause_CSharpKeyword";
}
return true;
}
}
text = null;
return false;
}
private static bool TryGetTextForCombinationKeyword(SyntaxToken token, ISyntaxFactsService syntaxFacts, out string text)
{
switch (token.Kind())
{
case SyntaxKind.PrivateKeyword when ModifiersContains(token, syntaxFacts, SyntaxKind.ProtectedKeyword):
case SyntaxKind.ProtectedKeyword when ModifiersContains(token, syntaxFacts, SyntaxKind.PrivateKeyword):
text = "privateprotected_CSharpKeyword";
return true;
case SyntaxKind.ProtectedKeyword when ModifiersContains(token, syntaxFacts, SyntaxKind.InternalKeyword):
case SyntaxKind.InternalKeyword when ModifiersContains(token, syntaxFacts, SyntaxKind.ProtectedKeyword):
text = "protectedinternal_CSharpKeyword";
return true;
case SyntaxKind.UsingKeyword when token.Parent is UsingDirectiveSyntax:
text = token.GetNextToken().IsKind(SyntaxKind.StaticKeyword)
? "using-static_CSharpKeyword"
: "using_CSharpKeyword";
return true;
case SyntaxKind.StaticKeyword when token.Parent is UsingDirectiveSyntax:
text = "using-static_CSharpKeyword";
return true;
}
text = null;
return false;
static bool ModifiersContains(SyntaxToken token, ISyntaxFactsService syntaxFacts, SyntaxKind kind)
{
return syntaxFacts.GetModifiers(token.Parent).Any(t => t.IsKind(kind));
}
}
private static bool TryGetTextForKeyword(SyntaxToken token, out string text)
{
if (token.IsKind(SyntaxKind.InKeyword))
{
if (token.GetAncestor<FromClauseSyntax>() != null)
{
text = "from_CSharpKeyword";
return true;
}
if (token.GetAncestor<JoinClauseSyntax>() != null)
{
text = "join_CSharpKeyword";
return true;
}
}
if (token.IsKind(SyntaxKind.DefaultKeyword) && token.Parent is DefaultSwitchLabelSyntax)
{
text = Keyword("defaultcase");
return true;
}
if (token.IsKind(SyntaxKind.ClassKeyword) && token.Parent is ClassOrStructConstraintSyntax)
{
text = Keyword("classconstraint");
return true;
}
if (token.IsKind(SyntaxKind.StructKeyword) && token.Parent is ClassOrStructConstraintSyntax)
{
text = Keyword("structconstraint");
return true;
}
if (token.IsKind(SyntaxKind.UsingKeyword) && token.Parent is UsingStatementSyntax or LocalDeclarationStatementSyntax)
{
text = Keyword("using-statement");
return true;
}
if (token.IsKeyword())
{
text = Keyword(token.Text);
return true;
}
if (token.ValueText == "var" && token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.Parent is VariableDeclarationSyntax declaration && token.Parent == declaration.Type)
{
text = "var_CSharpKeyword";
return true;
}
if (token.IsTypeNamedDynamic())
{
text = "dynamic_CSharpKeyword";
return true;
}
text = null;
return false;
}
private static string FormatNamespaceOrTypeSymbol(INamespaceOrTypeSymbol symbol)
{
var displayString = symbol.ToDisplayString(TypeFormat);
if (symbol is ITypeSymbol type && type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
return "System.Nullable`1";
}
if (symbol.GetTypeArguments().Any())
{
return $"{displayString}`{symbol.GetTypeArguments().Length}";
}
return displayString;
}
public override string FormatSymbol(ISymbol symbol)
{
if (symbol is ITypeSymbol || symbol is INamespaceSymbol)
{
return FormatNamespaceOrTypeSymbol((INamespaceOrTypeSymbol)symbol);
}
if (symbol.MatchesKind(SymbolKind.Alias, SymbolKind.Local, SymbolKind.Parameter))
{
return FormatSymbol(symbol.GetSymbolType());
}
var containingType = FormatNamespaceOrTypeSymbol(symbol.ContainingType);
var name = symbol.ToDisplayString(NameFormat);
if (symbol.IsConstructor())
{
return $"{containingType}.#ctor";
}
if (symbol.GetTypeArguments().Any())
{
return $"{containingType}.{name}``{symbol.GetTypeArguments().Length}";
}
return $"{containingType}.{name}";
}
}
}
| 1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.CSharp.LanguageServices
{
internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts
{
internal static readonly CSharpSyntaxFacts Instance = new();
protected CSharpSyntaxFacts()
{
}
public bool IsCaseSensitive => true;
public StringComparer StringComparer { get; } = StringComparer.Ordinal;
public SyntaxTrivia ElasticMarker
=> SyntaxFactory.ElasticMarker;
public SyntaxTrivia ElasticCarriageReturnLineFeed
=> SyntaxFactory.ElasticCarriageReturnLineFeed;
public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance;
public bool SupportsIndexingInitializer(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6;
public bool SupportsThrowExpression(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsLocalFunctionDeclaration(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsRecord(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9;
public bool SupportsRecordStruct(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove();
public SyntaxToken ParseToken(string text)
=> SyntaxFactory.ParseToken(text);
public SyntaxTriviaList ParseLeadingTrivia(string text)
=> SyntaxFactory.ParseLeadingTrivia(text);
public string EscapeIdentifier(string identifier)
{
var nullIndex = identifier.IndexOf('\0');
if (nullIndex >= 0)
{
identifier = identifier.Substring(0, nullIndex);
}
var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None;
return needsEscaping ? "@" + identifier : identifier;
}
public bool IsVerbatimIdentifier(SyntaxToken token)
=> token.IsVerbatimIdentifier();
public bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public bool IsReservedKeyword(SyntaxToken token)
=> SyntaxFacts.IsReservedKeyword(token.Kind());
public bool IsContextualKeyword(SyntaxToken token)
=> SyntaxFacts.IsContextualKeyword(token.Kind());
public bool IsPreprocessorKeyword(SyntaxToken token)
=> SyntaxFacts.IsPreprocessorKeyword(token.Kind());
public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
=> syntaxTree.IsPreProcessorDirectiveContext(
position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken)
{
if (syntaxTree == null)
{
return false;
}
return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public bool IsDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is DirectiveTriviaSyntax;
public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info)
{
if (node is LineDirectiveTriviaSyntax lineDirective)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default;
return false;
}
public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsSimpleMemberAccessExpressionName();
}
public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node;
public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberBindingExpressionName();
}
[return: NotNullIfNotNull("node")]
public SyntaxNode? GetStandaloneExpression(SyntaxNode? node)
=> node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node;
public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node)
=> node.GetRootConditionalAccessExpression();
public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is DeclarationExpressionSyntax;
public bool IsAttributeName(SyntaxNode node)
=> SyntaxFacts.IsAttributeName(node);
public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node is ArgumentSyntax arg && arg.NameColon != null;
public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.CheckParent<NameColonSyntax>(p => p.Name == node);
public SyntaxToken? GetNameOfParameter(SyntaxNode? node)
=> (node as ParameterSyntax)?.Identifier;
public SyntaxNode? GetDefaultOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Default;
public SyntaxNode? GetParameterList(SyntaxNode node)
=> node.GetParameterList();
public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList);
public SyntaxToken GetIdentifierOfGenericName(SyntaxNode node)
=> ((GenericNameSyntax)node).Identifier;
public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) &&
usingDirective.Name == node;
public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null;
public void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name)
{
var usingDirective = (UsingDirectiveSyntax)node;
globalKeyword = usingDirective.GlobalKeyword;
alias = usingDirective.Alias!.Name.Identifier;
name = usingDirective.Name;
}
public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is ForEachVariableStatementSyntax;
public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node)
=> node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction();
public Location GetDeconstructionReferenceLocation(SyntaxNode node)
{
return node switch
{
AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(),
ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(),
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
};
}
public bool IsStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node)
{
if (node is BlockSyntax ||
node is ArrowExpressionClauseSyntax)
{
return node.Parent is BaseMethodDeclarationSyntax ||
node.Parent is AccessorDeclarationSyntax;
}
return false;
}
public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node)
=> ((ReturnStatementSyntax)node).Expression;
public bool IsThisConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsBaseConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsQueryKeyword(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.FromKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.InKeyword:
return token.Parent is QueryClauseSyntax;
case SyntaxKind.ByKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.SelectKeyword:
return token.Parent is SelectOrGroupClauseSyntax;
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
return token.Parent is OrderingSyntax;
case SyntaxKind.IntoKeyword:
return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation);
default:
return false;
}
}
public bool IsPredefinedType(SyntaxToken token)
=> TryGetPredefinedType(token, out _);
public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
=> TryGetPredefinedType(token, out var actualType) && actualType == type;
public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private static PredefinedType GetPredefinedType(SyntaxToken token)
{
return (SyntaxKind)token.RawKind switch
{
SyntaxKind.BoolKeyword => PredefinedType.Boolean,
SyntaxKind.ByteKeyword => PredefinedType.Byte,
SyntaxKind.SByteKeyword => PredefinedType.SByte,
SyntaxKind.IntKeyword => PredefinedType.Int32,
SyntaxKind.UIntKeyword => PredefinedType.UInt32,
SyntaxKind.ShortKeyword => PredefinedType.Int16,
SyntaxKind.UShortKeyword => PredefinedType.UInt16,
SyntaxKind.LongKeyword => PredefinedType.Int64,
SyntaxKind.ULongKeyword => PredefinedType.UInt64,
SyntaxKind.FloatKeyword => PredefinedType.Single,
SyntaxKind.DoubleKeyword => PredefinedType.Double,
SyntaxKind.DecimalKeyword => PredefinedType.Decimal,
SyntaxKind.StringKeyword => PredefinedType.String,
SyntaxKind.CharKeyword => PredefinedType.Char,
SyntaxKind.ObjectKeyword => PredefinedType.Object,
SyntaxKind.VoidKeyword => PredefinedType.Void,
_ => PredefinedType.None,
};
}
public bool IsPredefinedOperator(SyntaxToken token)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None;
public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op;
public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private static PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanToken:
return PredefinedOperator.LessThan;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public string GetText(int kind)
=> SyntaxFacts.GetText((SyntaxKind)kind);
public bool IsIdentifierStartCharacter(char c)
=> SyntaxFacts.IsIdentifierStartCharacter(c);
public bool IsIdentifierPartCharacter(char c)
=> SyntaxFacts.IsIdentifierPartCharacter(c);
public bool IsIdentifierEscapeCharacter(char c)
=> c == '@';
public bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public bool IsTypeCharacter(char c) => false;
public bool IsStartOfUnicodeEscapeSequence(char c)
=> c == '\\';
public bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
return true;
default:
return false;
}
}
public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token)
=> token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken);
public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent)
{
var typedToken = token;
var typedParent = parent;
if (typedParent.IsKind(SyntaxKind.IdentifierName))
{
TypeSyntax? declaredType = null;
if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl))
{
declaredType = varDecl.Type;
}
else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl))
{
declaredType = fieldDecl.Declaration.Type;
}
return declaredType == typedParent && typedToken.ValueText == "var";
}
return false;
}
public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent)
{
if (parent is ExpressionSyntax typedParent)
{
if (SyntaxFacts.IsInTypeOnlyContext(typedParent) &&
typedParent.IsKind(SyntaxKind.IdentifierName) &&
token.ValueText == "dynamic")
{
return true;
}
}
return false;
}
public bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
// In the order by clause a comma might be bound to ThenBy or ThenByDescending
if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause))
{
return true;
}
return false;
}
public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is PostfixUnaryExpressionSyntax;
public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberBindingExpressionSyntax;
public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression;
public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity)
{
var simpleName = (SimpleNameSyntax)node;
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
public bool LooksGeneric(SyntaxNode simpleName)
=> simpleName.IsKind(SyntaxKind.GenericName) ||
simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken;
public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node)
=> (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression;
public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node)
=> ((MemberBindingExpressionSyntax)node).Name;
public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget)
=> ((MemberAccessExpressionSyntax)node).Expression;
public void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList)
{
var elementAccess = (ElementAccessExpressionSyntax)node;
expression = elementAccess.Expression;
argumentList = elementAccess.ArgumentList;
}
public SyntaxNode GetExpressionOfInterpolation(SyntaxNode node)
=> ((InterpolationSyntax)node).Expression;
public bool IsInStaticContext(SyntaxNode node)
=> node.IsInStaticContext();
public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node)
=> SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.BaseList);
public SyntaxNode GetExpressionOfArgument(SyntaxNode node)
=> ((ArgumentSyntax)node).Expression;
public RefKind GetRefKindOfArgument(SyntaxNode node)
=> ((ArgumentSyntax)node).GetRefKind();
public bool IsArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Argument);
public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node)
{
return node is ArgumentSyntax argument &&
argument.RefOrOutKeyword.Kind() == SyntaxKind.None &&
argument.NameColon == null;
}
public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsInConstantContext();
public bool IsInConstructor(SyntaxNode node)
=> node.GetAncestor<ConstructorDeclarationSyntax>() != null;
public bool IsUnsafeContext(SyntaxNode node)
=> node.IsUnsafeContext();
public SyntaxNode GetNameOfAttribute(SyntaxNode node)
=> ((AttributeSyntax)node).Name;
public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier();
public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node)
=> throw ExceptionUtilities.Unreachable;
public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IdentifierName) &&
node.IsParentKind(SyntaxKind.NameColon) &&
node.Parent.IsParentKind(SyntaxKind.Subpattern);
public bool IsPropertyPatternClause(SyntaxNode node)
=> node.Kind() == SyntaxKind.PropertyPatternClause;
public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> IsMemberInitializerNamedAssignmentIdentifier(node, out _);
public bool IsMemberInitializerNamedAssignmentIdentifier(
[NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance)
{
initializedInstance = null;
if (node is IdentifierNameSyntax identifier &&
identifier.IsLeftSideOfAssignExpression())
{
if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression))
{
var withInitializer = identifier.Parent.GetRequiredParent();
initializedInstance = withInitializer.GetRequiredParent();
return true;
}
else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression))
{
var objectInitializer = identifier.Parent.GetRequiredParent();
if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax)
{
initializedInstance = objectInitializer.Parent;
return true;
}
else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment))
{
initializedInstance = assignment.Left;
return true;
}
}
}
return false;
}
public bool IsElementAccessExpression(SyntaxNode? node)
=> node.IsKind(SyntaxKind.ElementAccessExpression);
[return: NotNullIfNotNull("node")]
public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false)
=> node.ConvertToSingleLine(useElasticTrivia);
public bool IsIndexerMemberCRef(SyntaxNode? node)
=> node.IsKind(SyntaxKind.IndexerMemberCref);
public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (useFullSpan || node.Span.Contains(position))
{
var kind = node.Kind();
if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax))
{
return node;
}
}
node = node.Parent;
}
return null;
}
public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseMethodDeclarationSyntax ||
node is BasePropertyDeclarationSyntax ||
node is EnumMemberDeclarationSyntax ||
node is BaseFieldDeclarationSyntax;
}
public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseNamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
private const string dotToken = ".";
public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null)
{
if (node == null)
{
return string.Empty;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
// return type
var memberDeclaration = node as MemberDeclarationSyntax;
if ((options & DisplayNameOptions.IncludeType) != 0)
{
var type = memberDeclaration.GetMemberType();
if (type != null && !type.IsMissing)
{
builder.Append(type);
builder.Append(' ');
}
}
var names = ArrayBuilder<string?>.GetInstance();
// containing type(s)
var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent;
while (parent is TypeDeclarationSyntax)
{
names.Push(GetName(parent, options));
parent = parent.Parent;
}
// containing namespace(s) in source (if any)
if ((options & DisplayNameOptions.IncludeNamespaces) != 0)
{
while (parent is BaseNamespaceDeclarationSyntax)
{
names.Add(GetName(parent, options));
parent = parent.Parent;
}
}
while (!names.IsEmpty())
{
var name = names.Pop();
if (name != null)
{
builder.Append(name);
builder.Append(dotToken);
}
}
// name (including generic type parameters)
builder.Append(GetName(node, options));
// parameter list (if any)
if ((options & DisplayNameOptions.IncludeParameters) != 0)
{
builder.Append(memberDeclaration.GetParameterList());
}
return pooled.ToStringAndFree();
}
private static string? GetName(SyntaxNode node, DisplayNameOptions options)
{
const string missingTokenPlaceholder = "?";
switch (node.Kind())
{
case SyntaxKind.CompilationUnit:
return null;
case SyntaxKind.IdentifierName:
var identifier = ((IdentifierNameSyntax)node).Identifier;
return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text;
case SyntaxKind.IncompleteMember:
return missingTokenPlaceholder;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options);
}
string? name = null;
if (node is MemberDeclarationSyntax memberDeclaration)
{
if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration)
{
name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString();
}
else
{
var nameToken = memberDeclaration.GetNameToken();
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration)
{
name = "~" + name;
}
if ((options & DisplayNameOptions.IncludeTypeParameters) != 0)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList());
name = pooled.ToStringAndFree();
}
}
else
{
Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember);
name = "?";
}
}
}
else
{
if (node is VariableDeclaratorSyntax fieldDeclarator)
{
var nameToken = fieldDeclarator.Identifier;
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
}
}
}
Debug.Assert(name != null, "Unexpected node type " + node.Kind());
return name;
}
private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (var i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(", ");
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
}
}
public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: true, methodLevel: true);
return list;
}
public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: false, methodLevel: true);
return list;
}
public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration)
=> ((TypeDeclarationSyntax)typeDeclaration).Members;
private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel)
{
Debug.Assert(topLevel || methodLevel);
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (topLevel)
{
list.Add(member);
}
AppendMembers(member, list, topLevel, methodLevel);
continue;
}
if (methodLevel && IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default;
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default;
}
// TODO: currently we only support method for now
if (member is BaseMethodDeclarationSyntax method)
{
if (method.Body == null)
{
return default;
}
return GetBlockBodySpan(method.Body);
}
return default;
}
public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span)
{
switch (node)
{
case ConstructorDeclarationSyntax constructor:
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
case BaseMethodDeclarationSyntax method:
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
case BasePropertyDeclarationSyntax property:
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
case EnumMemberDeclarationSyntax @enum:
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
case BaseFieldDeclarationSyntax field:
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private static TextSpan GetBlockBodySpan(BlockSyntax body)
=> TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
public SyntaxNode? TryGetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
if (parent is MemberAccessExpressionSyntax memberAccess)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is QualifiedNameSyntax qualifiedName)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
if (parent is ObjectCreationExpressionSyntax objectCreation)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// The inside of an interpolated string is treated as its own token so we
// need to force navigation to the parent expression syntax.
if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax)
{
node = parent;
break;
}
// If this node is not parented by a name, we're done.
if (!(parent is NameSyntax))
{
break;
}
node = parent;
}
if (node is VarPatternSyntax)
{
return node;
}
// Patterns are never bindable (though their constituent types/exprs may be).
return node is PatternSyntax ? null : node;
}
public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken)
{
if (root is not CompilationUnitSyntax compilationUnit)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
switch (member)
{
case ConstructorDeclarationSyntax constructor:
constructors.Add(constructor);
continue;
case BaseNamespaceDeclarationSyntax @namespace:
AppendConstructors(@namespace.Members, constructors, cancellationToken);
break;
case ClassDeclarationSyntax @class:
AppendConstructors(@class.Members, constructors, cancellationToken);
break;
case RecordDeclarationSyntax record:
AppendConstructors(record.Members, constructors, cancellationToken);
break;
case StructDeclarationSyntax @struct:
AppendConstructors(@struct.Members, constructors, cancellationToken);
break;
}
}
}
public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.openBrace;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default;
return false;
}
public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return trivia.FullSpan;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return default;
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return default;
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax branch)
{
return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default;
}
}
}
}
return default;
}
public string GetNameForArgument(SyntaxNode? argument)
=> (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty;
public string GetNameForAttributeArgument(SyntaxNode? argument)
=> (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty;
public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfDot();
public SyntaxNode? GetRightSideOfDot(SyntaxNode? node)
{
return (node as QualifiedNameSyntax)?.Right ??
(node as MemberAccessExpressionSyntax)?.Name;
}
public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget)
{
return (node as QualifiedNameSyntax)?.Left ??
(node as MemberAccessExpressionSyntax)?.Expression;
}
public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier();
public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAssignExpression();
public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression();
public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression();
public SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node)
=> ((AssignmentExpressionSyntax)node).Right;
public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) &&
anonObject.NameEquals == null;
public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostIncrementExpression) ||
node.IsParentKind(SyntaxKind.PreIncrementExpression);
public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostDecrementExpression) ||
node.IsParentKind(SyntaxKind.PreDecrementExpression);
public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node);
public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString)
=> ((InterpolatedStringExpressionSyntax)interpolatedString).Contents;
public bool IsVerbatimStringLiteral(SyntaxToken token)
=> token.IsVerbatimStringLiteral();
public bool IsNumericLiteral(SyntaxToken token)
=> token.Kind() == SyntaxKind.NumericLiteralToken;
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode invocationExpression)
=> GetArgumentsOfArgumentList(((InvocationExpressionSyntax)invocationExpression).ArgumentList);
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode objectCreationExpression)
=> ((BaseObjectCreationExpressionSyntax)objectCreationExpression).ArgumentList is { } argumentList
? GetArgumentsOfArgumentList(argumentList)
: default;
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode argumentList)
=> ((BaseArgumentListSyntax)argumentList).Arguments;
public bool IsRegularComment(SyntaxTrivia trivia)
=> trivia.IsRegularComment();
public bool IsDocumentationComment(SyntaxTrivia trivia)
=> trivia.IsDocComment();
public bool IsElastic(SyntaxTrivia trivia)
=> trivia.IsElastic();
public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes)
=> trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes);
public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia)
=> trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia;
public bool IsDocumentationComment(SyntaxNode node)
=> SyntaxFacts.IsDocumentationCommentTrivia(node.Kind());
public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node)
{
return node.IsKind(SyntaxKind.UsingDirective) ||
node.IsKind(SyntaxKind.ExternAliasDirective);
}
public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword);
public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.ModuleKeyword);
private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget)
=> node.IsKind(SyntaxKind.Attribute) &&
node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) &&
attributeList.Target?.Identifier.Kind() == attributeTarget;
private static bool IsMemberDeclaration(SyntaxNode node)
{
// From the C# language spec:
// class-member-declaration:
// constant-declaration
// field-declaration
// method-declaration
// property-declaration
// event-declaration
// indexer-declaration
// operator-declaration
// constructor-declaration
// destructor-declaration
// static-constructor-declaration
// type-declaration
switch (node.Kind())
{
// Because fields declarations can define multiple symbols "public int a, b;"
// We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
case SyntaxKind.VariableDeclarator:
return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) ||
node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
return true;
default:
return false;
}
}
public bool IsDeclaration(SyntaxNode node)
=> SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node);
public bool IsTypeDeclaration(SyntaxNode node)
=> SyntaxFacts.IsTypeDeclaration(node.Kind());
public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement)
=> statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) &&
exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression);
public void GetPartsOfAssignmentStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
GetPartsOfAssignmentExpressionOrStatement(
((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right);
}
public void GetPartsOfAssignmentExpressionOrStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var expression = statement;
if (statement is ExpressionStatementSyntax expressionStatement)
{
expression = expressionStatement.Expression;
}
var assignment = (AssignmentExpressionSyntax)expression;
left = assignment.Left;
operatorToken = assignment.OperatorToken;
right = assignment.Right;
}
public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node)
=> ((SimpleNameSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node)
=> node switch
{
BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier,
DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier,
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node)
=> ((IdentifierNameSyntax)node).Identifier;
public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement)
{
return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains(
(VariableDeclaratorSyntax)declarator);
}
public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2)
=> SyntaxFactory.AreEquivalent(token1, token2);
public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2)
=> SyntaxFactory.AreEquivalent(node1, node2);
public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node)
=> ((InvocationExpressionSyntax)node).Expression;
public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node;
public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node)
=> ((ExpressionStatementSyntax)node).Expression;
public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsExpression);
[return: NotNullIfNotNull("node")]
public SyntaxNode? WalkDownParentheses(SyntaxNode? node)
=> (node as ExpressionSyntax)?.WalkDownParentheses() ?? node;
public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode
{
var tupleExpression = (TupleExpressionSyntax)node;
openParen = tupleExpression.OpenParenToken;
arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments;
closeParen = tupleExpression.CloseParenToken;
}
public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement)
=> ((StatementSyntax)statement).GetNextStatement();
public override bool IsPreprocessorDirective(SyntaxTrivia trivia)
=> SyntaxFacts.IsPreprocessorDirective(trivia.Kind());
protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken)
=> token.ContainsInterleavedDirective(span, cancellationToken);
public SyntaxTokenList GetModifiers(SyntaxNode? node)
=> node.GetModifiers();
public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers)
=> node.WithModifiers(modifiers);
public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node)
=> ((LocalDeclarationStatementSyntax)node).Declaration.Variables;
public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Initializer;
public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type;
public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node)
=> ((EqualsValueClauseSyntax?)node)?.Value;
public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block);
public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit);
public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node)
{
return node switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement),
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
}
public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode(node => IsExecutableBlock(node));
public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node)
=> IsExecutableBlock(node) || node.IsEmbeddedStatementOwner();
public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node)
{
if (IsExecutableBlock(node))
return GetExecutableBlockStatements(node);
else if (node.GetEmbeddedStatement() is { } embeddedStatement)
return ImmutableArray.Create<SyntaxNode>(embeddedStatement);
else
return ImmutableArray<SyntaxNode>.Empty;
}
public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression)
{
var cast = (CastExpressionSyntax)node;
type = cast.Type;
expression = cast.Expression;
}
public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member)
{
return member.GetNameToken();
}
return null;
}
public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node)
=> node.GetAttributeLists();
public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) &&
xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName;
public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia)
{
if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia)
{
return documentationCommentTrivia.Content;
}
throw ExceptionUtilities.UnexpectedValue(trivia.Kind());
}
public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsPatternExpression);
public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right)
{
var isPatternExpression = (IsPatternExpressionSyntax)node;
left = isPatternExpression.Expression;
isToken = isPatternExpression.IsKeyword;
right = isPatternExpression.Pattern;
}
public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is PatternSyntax;
public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ConstantPattern);
public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.DeclarationPattern);
public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.RecursivePattern);
public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.VarPattern);
public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node)
=> ((ConstantPatternSyntax)node).Expression;
public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation)
{
var declarationPattern = (DeclarationPatternSyntax)node;
type = declarationPattern.Type;
designation = declarationPattern.Designation;
}
public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation)
{
var recursivePattern = (RecursivePatternSyntax)node;
type = recursivePattern.Type;
positionalPart = recursivePattern.PositionalPatternClause;
propertyPart = recursivePattern.PropertyPatternClause;
designation = recursivePattern.Designation;
}
public bool SupportsNotPattern(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove();
public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AndPattern);
public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryPatternSyntax;
public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.NotPattern);
public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.OrPattern);
public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParenthesizedPattern);
public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.TypePattern);
public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is UnaryPatternSyntax;
public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen)
{
var parenthesizedPattern = (ParenthesizedPatternSyntax)node;
openParen = parenthesizedPattern.OpenParenToken;
pattern = parenthesizedPattern.Pattern;
closeParen = parenthesizedPattern.CloseParenToken;
}
public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryPattern = (BinaryPatternSyntax)node;
left = binaryPattern.Left;
operatorToken = binaryPattern.OperatorToken;
right = binaryPattern.Right;
}
public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern)
{
var unaryPattern = (UnaryPatternSyntax)node;
operatorToken = unaryPattern.OperatorToken;
pattern = unaryPattern.Pattern;
}
public SyntaxNode GetTypeOfTypePattern(SyntaxNode node)
=> ((TypePatternSyntax)node).Type;
public void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken)
{
var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node;
stringStartToken = interpolatedStringExpression.StringStartToken;
contents = interpolatedStringExpression.Contents;
stringEndToken = interpolatedStringExpression.StringEndToken;
}
public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node)
=> node is InterpolatedStringExpressionSyntax interpolatedString &&
interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken);
#region IsXXX members
public bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is AnonymousFunctionExpressionSyntax;
public bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node is BaseNamespaceDeclarationSyntax;
public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryExpressionSyntax;
public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is LiteralExpressionSyntax;
public bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberAccessExpressionSyntax;
public bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node)
=> node is SimpleNameSyntax;
#endregion
#region GetPartsOfXXX members
public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryExpression = (BinaryExpressionSyntax)node;
left = binaryExpression.Left;
operatorToken = binaryExpression.OperatorToken;
right = binaryExpression.Right;
}
public void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members)
{
var compilationUnit = (CompilationUnitSyntax)node;
imports = compilationUnit.Usings;
attributeLists = compilationUnit.AttributeLists;
members = compilationUnit.Members;
}
public void GetPartsOfConditionalAccessExpression(
SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull)
{
var conditionalAccess = (ConditionalAccessExpressionSyntax)node;
expression = conditionalAccess.Expression;
operatorToken = conditionalAccess.OperatorToken;
whenNotNull = conditionalAccess.WhenNotNull;
}
public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse)
{
var conditionalExpression = (ConditionalExpressionSyntax)node;
condition = conditionalExpression.Condition;
whenTrue = conditionalExpression.WhenTrue;
whenFalse = conditionalExpression.WhenFalse;
}
public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList)
{
var invocation = (InvocationExpressionSyntax)node;
expression = invocation.Expression;
argumentList = invocation.ArgumentList;
}
public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name)
{
var memberAccess = (MemberAccessExpressionSyntax)node;
expression = memberAccess.Expression;
operatorToken = memberAccess.OperatorToken;
name = memberAccess.Name;
}
public void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members)
{
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)node;
name = namespaceDeclaration.Name;
imports = namespaceDeclaration.Usings;
members = namespaceDeclaration.Members;
}
public void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer)
{
var objectCreationExpression = (ObjectCreationExpressionSyntax)node;
type = objectCreationExpression.Type;
argumentList = objectCreationExpression.ArgumentList;
initializer = objectCreationExpression.Initializer;
}
public void GetPartsOfParenthesizedExpression(
SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen)
{
var parenthesizedExpression = (ParenthesizedExpressionSyntax)node;
openParen = parenthesizedExpression.OpenParenToken;
expression = parenthesizedExpression.Expression;
closeParen = parenthesizedExpression.CloseParenToken;
}
public void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand)
{
var prefixUnaryExpression = (PrefixUnaryExpressionSyntax)node;
operatorToken = prefixUnaryExpression.OperatorToken;
operand = prefixUnaryExpression.Operand;
}
public void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var qualifiedName = (QualifiedNameSyntax)node;
left = qualifiedName.Left;
operatorToken = qualifiedName.DotToken;
right = qualifiedName.Right;
}
#endregion
#region GetXXXOfYYY members
public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node)
=> ((AwaitExpressionSyntax)node).Expression;
public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node)
=> ((ThrowExpressionSyntax)node).Expression;
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.CSharp.LanguageServices
{
internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts
{
internal static readonly CSharpSyntaxFacts Instance = new();
protected CSharpSyntaxFacts()
{
}
public bool IsCaseSensitive => true;
public StringComparer StringComparer { get; } = StringComparer.Ordinal;
public SyntaxTrivia ElasticMarker
=> SyntaxFactory.ElasticMarker;
public SyntaxTrivia ElasticCarriageReturnLineFeed
=> SyntaxFactory.ElasticCarriageReturnLineFeed;
public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance;
public bool SupportsIndexingInitializer(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6;
public bool SupportsThrowExpression(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsLocalFunctionDeclaration(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7;
public bool SupportsRecord(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9;
public bool SupportsRecordStruct(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove();
public SyntaxToken ParseToken(string text)
=> SyntaxFactory.ParseToken(text);
public SyntaxTriviaList ParseLeadingTrivia(string text)
=> SyntaxFactory.ParseLeadingTrivia(text);
public string EscapeIdentifier(string identifier)
{
var nullIndex = identifier.IndexOf('\0');
if (nullIndex >= 0)
{
identifier = identifier.Substring(0, nullIndex);
}
var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None;
return needsEscaping ? "@" + identifier : identifier;
}
public bool IsVerbatimIdentifier(SyntaxToken token)
=> token.IsVerbatimIdentifier();
public bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public bool IsReservedKeyword(SyntaxToken token)
=> SyntaxFacts.IsReservedKeyword(token.Kind());
public bool IsContextualKeyword(SyntaxToken token)
=> SyntaxFacts.IsContextualKeyword(token.Kind());
public bool IsPreprocessorKeyword(SyntaxToken token)
=> SyntaxFacts.IsPreprocessorKeyword(token.Kind());
public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
=> syntaxTree.IsPreProcessorDirectiveContext(
position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken)
{
if (syntaxTree == null)
{
return false;
}
return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public bool IsDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is DirectiveTriviaSyntax;
public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info)
{
if (node is LineDirectiveTriviaSyntax lineDirective)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default;
return false;
}
public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsSimpleMemberAccessExpressionName();
}
public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node;
public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberBindingExpressionName();
}
[return: NotNullIfNotNull("node")]
public SyntaxNode? GetStandaloneExpression(SyntaxNode? node)
=> node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node;
public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node)
=> node.GetRootConditionalAccessExpression();
public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is DeclarationExpressionSyntax;
public bool IsAttributeName(SyntaxNode node)
=> SyntaxFacts.IsAttributeName(node);
public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node is ArgumentSyntax arg && arg.NameColon != null;
public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.CheckParent<NameColonSyntax>(p => p.Name == node);
public SyntaxToken? GetNameOfParameter(SyntaxNode? node)
=> (node as ParameterSyntax)?.Identifier;
public SyntaxNode? GetDefaultOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Default;
public SyntaxNode? GetParameterList(SyntaxNode node)
=> node.GetParameterList();
public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList);
public SyntaxToken GetIdentifierOfGenericName(SyntaxNode node)
=> ((GenericNameSyntax)node).Identifier;
public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) &&
usingDirective.Name == node;
public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node)
=> node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null;
public void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name)
{
var usingDirective = (UsingDirectiveSyntax)node;
globalKeyword = usingDirective.GlobalKeyword;
alias = usingDirective.Alias!.Name.Identifier;
name = usingDirective.Name;
}
public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is ForEachVariableStatementSyntax;
public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node)
=> node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction();
public Location GetDeconstructionReferenceLocation(SyntaxNode node)
{
return node switch
{
AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(),
ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(),
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
};
}
public bool IsStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node)
=> node is StatementSyntax;
public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node)
{
if (node is BlockSyntax ||
node is ArrowExpressionClauseSyntax)
{
return node.Parent is BaseMethodDeclarationSyntax ||
node.Parent is AccessorDeclarationSyntax;
}
return false;
}
public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node)
=> ((ReturnStatementSyntax)node).Expression;
public bool IsThisConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsBaseConstructorInitializer(SyntaxToken token)
=> token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) &&
constructorInit.ThisOrBaseKeyword == token;
public bool IsQueryKeyword(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.FromKeyword:
case SyntaxKind.JoinKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.OrderByKeyword:
case SyntaxKind.WhereKeyword:
case SyntaxKind.OnKeyword:
case SyntaxKind.EqualsKeyword:
case SyntaxKind.InKeyword:
return token.Parent is QueryClauseSyntax;
case SyntaxKind.ByKeyword:
case SyntaxKind.GroupKeyword:
case SyntaxKind.SelectKeyword:
return token.Parent is SelectOrGroupClauseSyntax;
case SyntaxKind.AscendingKeyword:
case SyntaxKind.DescendingKeyword:
return token.Parent is OrderingSyntax;
case SyntaxKind.IntoKeyword:
return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation);
default:
return false;
}
}
public bool IsPredefinedType(SyntaxToken token)
=> TryGetPredefinedType(token, out _);
public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
=> TryGetPredefinedType(token, out var actualType) && actualType == type;
public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private static PredefinedType GetPredefinedType(SyntaxToken token)
{
return (SyntaxKind)token.RawKind switch
{
SyntaxKind.BoolKeyword => PredefinedType.Boolean,
SyntaxKind.ByteKeyword => PredefinedType.Byte,
SyntaxKind.SByteKeyword => PredefinedType.SByte,
SyntaxKind.IntKeyword => PredefinedType.Int32,
SyntaxKind.UIntKeyword => PredefinedType.UInt32,
SyntaxKind.ShortKeyword => PredefinedType.Int16,
SyntaxKind.UShortKeyword => PredefinedType.UInt16,
SyntaxKind.LongKeyword => PredefinedType.Int64,
SyntaxKind.ULongKeyword => PredefinedType.UInt64,
SyntaxKind.FloatKeyword => PredefinedType.Single,
SyntaxKind.DoubleKeyword => PredefinedType.Double,
SyntaxKind.DecimalKeyword => PredefinedType.Decimal,
SyntaxKind.StringKeyword => PredefinedType.String,
SyntaxKind.CharKeyword => PredefinedType.Char,
SyntaxKind.ObjectKeyword => PredefinedType.Object,
SyntaxKind.VoidKeyword => PredefinedType.Void,
_ => PredefinedType.None,
};
}
public bool IsPredefinedOperator(SyntaxToken token)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None;
public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
=> TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op;
public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private static PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanToken:
return PredefinedOperator.LessThan;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public string GetText(int kind)
=> SyntaxFacts.GetText((SyntaxKind)kind);
public bool IsIdentifierStartCharacter(char c)
=> SyntaxFacts.IsIdentifierStartCharacter(c);
public bool IsIdentifierPartCharacter(char c)
=> SyntaxFacts.IsIdentifierPartCharacter(c);
public bool IsIdentifierEscapeCharacter(char c)
=> c == '@';
public bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public bool IsTypeCharacter(char c) => false;
public bool IsStartOfUnicodeEscapeSequence(char c)
=> c == '\\';
public bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
return true;
default:
return false;
}
}
public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token)
=> token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken);
public bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
// In the order by clause a comma might be bound to ThenBy or ThenByDescending
if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause))
{
return true;
}
return false;
}
public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is PostfixUnaryExpressionSyntax;
public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberBindingExpressionSyntax;
public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression;
public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity)
{
var simpleName = (SimpleNameSyntax)node;
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
public bool LooksGeneric(SyntaxNode simpleName)
=> simpleName.IsKind(SyntaxKind.GenericName) ||
simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken;
public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node)
=> (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression;
public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node)
=> ((MemberBindingExpressionSyntax)node).Name;
public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget)
=> ((MemberAccessExpressionSyntax)node).Expression;
public void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList)
{
var elementAccess = (ElementAccessExpressionSyntax)node;
expression = elementAccess.Expression;
argumentList = elementAccess.ArgumentList;
}
public SyntaxNode GetExpressionOfInterpolation(SyntaxNode node)
=> ((InterpolationSyntax)node).Expression;
public bool IsInStaticContext(SyntaxNode node)
=> node.IsInStaticContext();
public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node)
=> SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.BaseList);
public SyntaxNode GetExpressionOfArgument(SyntaxNode node)
=> ((ArgumentSyntax)node).Expression;
public RefKind GetRefKindOfArgument(SyntaxNode node)
=> ((ArgumentSyntax)node).GetRefKind();
public bool IsArgument([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Argument);
public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node)
{
return node is ArgumentSyntax argument &&
argument.RefOrOutKeyword.Kind() == SyntaxKind.None &&
argument.NameColon == null;
}
public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsInConstantContext();
public bool IsInConstructor(SyntaxNode node)
=> node.GetAncestor<ConstructorDeclarationSyntax>() != null;
public bool IsUnsafeContext(SyntaxNode node)
=> node.IsUnsafeContext();
public SyntaxNode GetNameOfAttribute(SyntaxNode node)
=> ((AttributeSyntax)node).Name;
public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier();
public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node)
=> throw ExceptionUtilities.Unreachable;
public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IdentifierName) &&
node.IsParentKind(SyntaxKind.NameColon) &&
node.Parent.IsParentKind(SyntaxKind.Subpattern);
public bool IsPropertyPatternClause(SyntaxNode node)
=> node.Kind() == SyntaxKind.PropertyPatternClause;
public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node)
=> IsMemberInitializerNamedAssignmentIdentifier(node, out _);
public bool IsMemberInitializerNamedAssignmentIdentifier(
[NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance)
{
initializedInstance = null;
if (node is IdentifierNameSyntax identifier &&
identifier.IsLeftSideOfAssignExpression())
{
if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression))
{
var withInitializer = identifier.Parent.GetRequiredParent();
initializedInstance = withInitializer.GetRequiredParent();
return true;
}
else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression))
{
var objectInitializer = identifier.Parent.GetRequiredParent();
if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax)
{
initializedInstance = objectInitializer.Parent;
return true;
}
else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment))
{
initializedInstance = assignment.Left;
return true;
}
}
}
return false;
}
public bool IsElementAccessExpression(SyntaxNode? node)
=> node.IsKind(SyntaxKind.ElementAccessExpression);
[return: NotNullIfNotNull("node")]
public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false)
=> node.ConvertToSingleLine(useElasticTrivia);
public bool IsIndexerMemberCRef(SyntaxNode? node)
=> node.IsKind(SyntaxKind.IndexerMemberCref);
public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (useFullSpan || node.Span.Contains(position))
{
var kind = node.Kind();
if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax))
{
return node;
}
}
node = node.Parent;
}
return null;
}
public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseMethodDeclarationSyntax ||
node is BasePropertyDeclarationSyntax ||
node is EnumMemberDeclarationSyntax ||
node is BaseFieldDeclarationSyntax;
}
public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node)
{
return node is BaseNamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
private const string dotToken = ".";
public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null)
{
if (node == null)
{
return string.Empty;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
// return type
var memberDeclaration = node as MemberDeclarationSyntax;
if ((options & DisplayNameOptions.IncludeType) != 0)
{
var type = memberDeclaration.GetMemberType();
if (type != null && !type.IsMissing)
{
builder.Append(type);
builder.Append(' ');
}
}
var names = ArrayBuilder<string?>.GetInstance();
// containing type(s)
var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent;
while (parent is TypeDeclarationSyntax)
{
names.Push(GetName(parent, options));
parent = parent.Parent;
}
// containing namespace(s) in source (if any)
if ((options & DisplayNameOptions.IncludeNamespaces) != 0)
{
while (parent is BaseNamespaceDeclarationSyntax)
{
names.Add(GetName(parent, options));
parent = parent.Parent;
}
}
while (!names.IsEmpty())
{
var name = names.Pop();
if (name != null)
{
builder.Append(name);
builder.Append(dotToken);
}
}
// name (including generic type parameters)
builder.Append(GetName(node, options));
// parameter list (if any)
if ((options & DisplayNameOptions.IncludeParameters) != 0)
{
builder.Append(memberDeclaration.GetParameterList());
}
return pooled.ToStringAndFree();
}
private static string? GetName(SyntaxNode node, DisplayNameOptions options)
{
const string missingTokenPlaceholder = "?";
switch (node.Kind())
{
case SyntaxKind.CompilationUnit:
return null;
case SyntaxKind.IdentifierName:
var identifier = ((IdentifierNameSyntax)node).Identifier;
return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text;
case SyntaxKind.IncompleteMember:
return missingTokenPlaceholder;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options);
}
string? name = null;
if (node is MemberDeclarationSyntax memberDeclaration)
{
if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration)
{
name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString();
}
else
{
var nameToken = memberDeclaration.GetNameToken();
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration)
{
name = "~" + name;
}
if ((options & DisplayNameOptions.IncludeTypeParameters) != 0)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList());
name = pooled.ToStringAndFree();
}
}
else
{
Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember);
name = "?";
}
}
}
else
{
if (node is VariableDeclaratorSyntax fieldDeclarator)
{
var nameToken = fieldDeclarator.Identifier;
if (nameToken != default)
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
}
}
}
Debug.Assert(name != null, "Unexpected node type " + node.Kind());
return name;
}
private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (var i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(", ");
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
}
}
public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: true, methodLevel: true);
return list;
}
public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root)
{
var list = new List<SyntaxNode>();
AppendMembers(root, list, topLevel: false, methodLevel: true);
return list;
}
public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration)
=> ((TypeDeclarationSyntax)typeDeclaration).Members;
private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel)
{
Debug.Assert(topLevel || methodLevel);
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (topLevel)
{
list.Add(member);
}
AppendMembers(member, list, topLevel, methodLevel);
continue;
}
if (methodLevel && IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default;
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default;
}
// TODO: currently we only support method for now
if (member is BaseMethodDeclarationSyntax method)
{
if (method.Body == null)
{
return default;
}
return GetBlockBodySpan(method.Body);
}
return default;
}
public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span)
{
switch (node)
{
case ConstructorDeclarationSyntax constructor:
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
case BaseMethodDeclarationSyntax method:
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
case BasePropertyDeclarationSyntax property:
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
case EnumMemberDeclarationSyntax @enum:
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
case BaseFieldDeclarationSyntax field:
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private static TextSpan GetBlockBodySpan(BlockSyntax body)
=> TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
public SyntaxNode? TryGetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
if (parent is MemberAccessExpressionSyntax memberAccess)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is QualifiedNameSyntax qualifiedName)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
if (parent is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
if (parent is ObjectCreationExpressionSyntax objectCreation)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// The inside of an interpolated string is treated as its own token so we
// need to force navigation to the parent expression syntax.
if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax)
{
node = parent;
break;
}
// If this node is not parented by a name, we're done.
if (!(parent is NameSyntax))
{
break;
}
node = parent;
}
if (node is VarPatternSyntax)
{
return node;
}
// Patterns are never bindable (though their constituent types/exprs may be).
return node is PatternSyntax ? null : node;
}
public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken)
{
if (root is not CompilationUnitSyntax compilationUnit)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
switch (member)
{
case ConstructorDeclarationSyntax constructor:
constructors.Add(constructor);
continue;
case BaseNamespaceDeclarationSyntax @namespace:
AppendConstructors(@namespace.Members, constructors, cancellationToken);
break;
case ClassDeclarationSyntax @class:
AppendConstructors(@class.Members, constructors, cancellationToken);
break;
case RecordDeclarationSyntax record:
AppendConstructors(record.Members, constructors, cancellationToken);
break;
case StructDeclarationSyntax @struct:
AppendConstructors(@struct.Members, constructors, cancellationToken);
break;
}
}
}
public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.openBrace;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default;
return false;
}
public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return trivia.FullSpan;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return default;
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return default;
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax branch)
{
return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default;
}
}
}
}
return default;
}
public string GetNameForArgument(SyntaxNode? argument)
=> (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty;
public string GetNameForAttributeArgument(SyntaxNode? argument)
=> (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty;
public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfDot();
public SyntaxNode? GetRightSideOfDot(SyntaxNode? node)
{
return (node as QualifiedNameSyntax)?.Right ??
(node as MemberAccessExpressionSyntax)?.Name;
}
public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget)
{
return (node as QualifiedNameSyntax)?.Left ??
(node as MemberAccessExpressionSyntax)?.Expression;
}
public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node)
=> (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier();
public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAssignExpression();
public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression();
public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node)
=> (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression();
public SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node)
=> ((AssignmentExpressionSyntax)node).Right;
public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) &&
anonObject.NameEquals == null;
public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostIncrementExpression) ||
node.IsParentKind(SyntaxKind.PreIncrementExpression);
public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.PostDecrementExpression) ||
node.IsParentKind(SyntaxKind.PreDecrementExpression);
public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node)
=> IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node);
public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString)
=> ((InterpolatedStringExpressionSyntax)interpolatedString).Contents;
public bool IsVerbatimStringLiteral(SyntaxToken token)
=> token.IsVerbatimStringLiteral();
public bool IsNumericLiteral(SyntaxToken token)
=> token.Kind() == SyntaxKind.NumericLiteralToken;
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode invocationExpression)
=> GetArgumentsOfArgumentList(((InvocationExpressionSyntax)invocationExpression).ArgumentList);
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode objectCreationExpression)
=> ((BaseObjectCreationExpressionSyntax)objectCreationExpression).ArgumentList is { } argumentList
? GetArgumentsOfArgumentList(argumentList)
: default;
public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode argumentList)
=> ((BaseArgumentListSyntax)argumentList).Arguments;
public bool IsRegularComment(SyntaxTrivia trivia)
=> trivia.IsRegularComment();
public bool IsDocumentationComment(SyntaxTrivia trivia)
=> trivia.IsDocComment();
public bool IsElastic(SyntaxTrivia trivia)
=> trivia.IsElastic();
public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes)
=> trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes);
public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia)
=> trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia;
public bool IsDocumentationComment(SyntaxNode node)
=> SyntaxFacts.IsDocumentationCommentTrivia(node.Kind());
public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node)
{
return node.IsKind(SyntaxKind.UsingDirective) ||
node.IsKind(SyntaxKind.ExternAliasDirective);
}
public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword);
public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node)
=> IsGlobalAttribute(node, SyntaxKind.ModuleKeyword);
private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget)
=> node.IsKind(SyntaxKind.Attribute) &&
node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) &&
attributeList.Target?.Identifier.Kind() == attributeTarget;
private static bool IsMemberDeclaration(SyntaxNode node)
{
// From the C# language spec:
// class-member-declaration:
// constant-declaration
// field-declaration
// method-declaration
// property-declaration
// event-declaration
// indexer-declaration
// operator-declaration
// constructor-declaration
// destructor-declaration
// static-constructor-declaration
// type-declaration
switch (node.Kind())
{
// Because fields declarations can define multiple symbols "public int a, b;"
// We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
case SyntaxKind.VariableDeclarator:
return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) ||
node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
return true;
default:
return false;
}
}
public bool IsDeclaration(SyntaxNode node)
=> SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node);
public bool IsTypeDeclaration(SyntaxNode node)
=> SyntaxFacts.IsTypeDeclaration(node.Kind());
public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement)
=> statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) &&
exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression);
public void GetPartsOfAssignmentStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
GetPartsOfAssignmentExpressionOrStatement(
((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right);
}
public void GetPartsOfAssignmentExpressionOrStatement(
SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var expression = statement;
if (statement is ExpressionStatementSyntax expressionStatement)
{
expression = expressionStatement.Expression;
}
var assignment = (AssignmentExpressionSyntax)expression;
left = assignment.Left;
operatorToken = assignment.OperatorToken;
right = assignment.Right;
}
public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node)
=> ((SimpleNameSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfParameter(SyntaxNode node)
=> ((ParameterSyntax)node).Identifier;
public SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node)
=> node switch
{
BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier,
DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier,
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node)
=> ((IdentifierNameSyntax)node).Identifier;
public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement)
{
return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains(
(VariableDeclaratorSyntax)declarator);
}
public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2)
=> SyntaxFactory.AreEquivalent(token1, token2);
public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2)
=> SyntaxFactory.AreEquivalent(node1, node2);
public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node)
=> ((InvocationExpressionSyntax)node).Expression;
public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node)
=> node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node;
public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node)
=> ((ExpressionStatementSyntax)node).Expression;
public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsExpression);
[return: NotNullIfNotNull("node")]
public SyntaxNode? WalkDownParentheses(SyntaxNode? node)
=> (node as ExpressionSyntax)?.WalkDownParentheses() ?? node;
public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode
{
var tupleExpression = (TupleExpressionSyntax)node;
openParen = tupleExpression.OpenParenToken;
arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments;
closeParen = tupleExpression.CloseParenToken;
}
public override bool IsPreprocessorDirective(SyntaxTrivia trivia)
=> SyntaxFacts.IsPreprocessorDirective(trivia.Kind());
protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken)
=> token.ContainsInterleavedDirective(span, cancellationToken);
public SyntaxTokenList GetModifiers(SyntaxNode? node)
=> node.GetModifiers();
public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers)
=> node.WithModifiers(modifiers);
public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node)
=> ((LocalDeclarationStatementSyntax)node).Declaration.Variables;
public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclaratorSyntax)node).Initializer;
public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node)
=> ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type;
public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node)
=> ((EqualsValueClauseSyntax?)node)?.Value;
public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block);
public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit);
public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node)
{
return node switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement),
_ => throw ExceptionUtilities.UnexpectedValue(node),
};
}
public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode(node => IsExecutableBlock(node));
public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node)
=> IsExecutableBlock(node) || node.IsEmbeddedStatementOwner();
public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node)
{
if (IsExecutableBlock(node))
return GetExecutableBlockStatements(node);
else if (node.GetEmbeddedStatement() is { } embeddedStatement)
return ImmutableArray.Create<SyntaxNode>(embeddedStatement);
else
return ImmutableArray<SyntaxNode>.Empty;
}
public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is CastExpressionSyntax;
public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression)
{
var cast = (CastExpressionSyntax)node;
type = cast.Type;
expression = cast.Expression;
}
public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member)
{
return member.GetNameToken();
}
return null;
}
public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node)
=> node.GetAttributeLists();
public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) &&
xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName;
public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia)
{
if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia)
{
return documentationCommentTrivia.Content;
}
throw ExceptionUtilities.UnexpectedValue(trivia.Kind());
}
public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.IsPatternExpression);
public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right)
{
var isPatternExpression = (IsPatternExpressionSyntax)node;
left = isPatternExpression.Expression;
isToken = isPatternExpression.IsKeyword;
right = isPatternExpression.Pattern;
}
public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is PatternSyntax;
public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ConstantPattern);
public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.DeclarationPattern);
public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.RecursivePattern);
public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.VarPattern);
public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node)
=> ((ConstantPatternSyntax)node).Expression;
public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation)
{
var declarationPattern = (DeclarationPatternSyntax)node;
type = declarationPattern.Type;
designation = declarationPattern.Designation;
}
public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation)
{
var recursivePattern = (RecursivePatternSyntax)node;
type = recursivePattern.Type;
positionalPart = recursivePattern.PositionalPatternClause;
propertyPart = recursivePattern.PropertyPatternClause;
designation = recursivePattern.Designation;
}
public bool SupportsNotPattern(ParseOptions options)
=> ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove();
public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.AndPattern);
public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryPatternSyntax;
public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.NotPattern);
public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.OrPattern);
public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.ParenthesizedPattern);
public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node)
=> node.IsKind(SyntaxKind.TypePattern);
public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node)
=> node is UnaryPatternSyntax;
public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen)
{
var parenthesizedPattern = (ParenthesizedPatternSyntax)node;
openParen = parenthesizedPattern.OpenParenToken;
pattern = parenthesizedPattern.Pattern;
closeParen = parenthesizedPattern.CloseParenToken;
}
public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryPattern = (BinaryPatternSyntax)node;
left = binaryPattern.Left;
operatorToken = binaryPattern.OperatorToken;
right = binaryPattern.Right;
}
public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern)
{
var unaryPattern = (UnaryPatternSyntax)node;
operatorToken = unaryPattern.OperatorToken;
pattern = unaryPattern.Pattern;
}
public SyntaxNode GetTypeOfTypePattern(SyntaxNode node)
=> ((TypePatternSyntax)node).Type;
public void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken)
{
var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node;
stringStartToken = interpolatedStringExpression.StringStartToken;
contents = interpolatedStringExpression.Contents;
stringEndToken = interpolatedStringExpression.StringEndToken;
}
public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node)
=> node is InterpolatedStringExpressionSyntax interpolatedString &&
interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken);
#region IsXXX members
public bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is AnonymousFunctionExpressionSyntax;
public bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node)
=> node is BaseNamespaceDeclarationSyntax;
public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is BinaryExpressionSyntax;
public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is LiteralExpressionSyntax;
public bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node)
=> node is MemberAccessExpressionSyntax;
public bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node)
=> node is SimpleNameSyntax;
#endregion
#region GetPartsOfXXX members
public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var binaryExpression = (BinaryExpressionSyntax)node;
left = binaryExpression.Left;
operatorToken = binaryExpression.OperatorToken;
right = binaryExpression.Right;
}
public void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members)
{
var compilationUnit = (CompilationUnitSyntax)node;
imports = compilationUnit.Usings;
attributeLists = compilationUnit.AttributeLists;
members = compilationUnit.Members;
}
public void GetPartsOfConditionalAccessExpression(
SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull)
{
var conditionalAccess = (ConditionalAccessExpressionSyntax)node;
expression = conditionalAccess.Expression;
operatorToken = conditionalAccess.OperatorToken;
whenNotNull = conditionalAccess.WhenNotNull;
}
public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse)
{
var conditionalExpression = (ConditionalExpressionSyntax)node;
condition = conditionalExpression.Condition;
whenTrue = conditionalExpression.WhenTrue;
whenFalse = conditionalExpression.WhenFalse;
}
public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList)
{
var invocation = (InvocationExpressionSyntax)node;
expression = invocation.Expression;
argumentList = invocation.ArgumentList;
}
public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name)
{
var memberAccess = (MemberAccessExpressionSyntax)node;
expression = memberAccess.Expression;
operatorToken = memberAccess.OperatorToken;
name = memberAccess.Name;
}
public void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members)
{
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)node;
name = namespaceDeclaration.Name;
imports = namespaceDeclaration.Usings;
members = namespaceDeclaration.Members;
}
public void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer)
{
var objectCreationExpression = (ObjectCreationExpressionSyntax)node;
type = objectCreationExpression.Type;
argumentList = objectCreationExpression.ArgumentList;
initializer = objectCreationExpression.Initializer;
}
public void GetPartsOfParenthesizedExpression(
SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen)
{
var parenthesizedExpression = (ParenthesizedExpressionSyntax)node;
openParen = parenthesizedExpression.OpenParenToken;
expression = parenthesizedExpression.Expression;
closeParen = parenthesizedExpression.CloseParenToken;
}
public void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand)
{
var prefixUnaryExpression = (PrefixUnaryExpressionSyntax)node;
operatorToken = prefixUnaryExpression.OperatorToken;
operand = prefixUnaryExpression.Operand;
}
public void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right)
{
var qualifiedName = (QualifiedNameSyntax)node;
left = qualifiedName.Left;
operatorToken = qualifiedName.DotToken;
right = qualifiedName.Right;
}
#endregion
#region GetXXXOfYYY members
public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node)
=> ((AwaitExpressionSyntax)node).Expression;
public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node)
=> ((ThrowExpressionSyntax)node).Expression;
#endregion
}
}
| 1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
/// <summary>
/// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion.
/// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform
/// fashion over the languages. Helpers in this type should only be one of the following forms:
/// <list type="bullet">
/// <item>
/// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that
/// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking'
/// methods should never fail. For non leaf node types this should be implemented as a typecheck ('is' in C#, 'typeof ... is'
/// in VB). For leaf nodes, this should be implemented by deffering to <see cref="ISyntaxKinds"/> to check against the
/// raw kind of the node.
/// </item>
/// <item>
/// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs
/// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the
/// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)'
/// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for.
/// For nodes that only have a single child, 'GetPartsOfXXX' is not not needed and can be replaced with the easier to use
/// 'GetXXXOfYYY' to get that single child.
/// </item>
/// <item>
/// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For
/// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and
/// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for.
/// For nodes that only have a single child, these functions can stay here. For nodes with multiple children, these should migrate
/// to <see cref="ISyntaxFactsExtensions"/> and be built off of 'GetPartsOfXXX'.
/// </item>
/// <item>
/// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example,
/// if certain constructs (like 'patterns') are supported in that language or not.
/// </item>
/// </list>
///
/// <para>Importantly, avoid:</para>
///
/// <list type="bullet">
/// <item>
/// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName
/// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context).
/// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right
/// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts).
/// </item>
/// <item>
/// Functions which are effectively specific to a single feature are are just trying to find a place to place complex
/// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position
/// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of
/// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in
/// its own dedicated service.
/// </item>
/// <item>
/// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or
/// some other feature specific service.
/// </item>
/// <item>
/// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'.
/// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle
/// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs
/// to creep in.
/// </item>
/// <item>
/// Abbreviating or otherwise changing the names that C# and VB share here. For example use 'ObjectCreationExpression'
/// not 'ObjectCreation'. This prevents accidental duplication and keeps consistency with all members.
/// </item>
/// </list>
/// </summary>
/// <remarks>
/// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either
/// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service
/// for that purpose if needed by multiple features.
/// </remarks>
internal interface ISyntaxFacts
{
bool IsCaseSensitive { get; }
StringComparer StringComparer { get; }
SyntaxTrivia ElasticMarker { get; }
SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
ISyntaxKinds SyntaxKinds { get; }
bool SupportsIndexingInitializer(ParseOptions options);
bool SupportsLocalFunctionDeclaration(ParseOptions options);
bool SupportsNotPattern(ParseOptions options);
bool SupportsRecord(ParseOptions options);
bool SupportsRecordStruct(ParseOptions options);
bool SupportsThrowExpression(ParseOptions options);
SyntaxToken ParseToken(string text);
SyntaxTriviaList ParseLeadingTrivia(string text);
string EscapeIdentifier(string identifier);
bool IsVerbatimIdentifier(SyntaxToken token);
bool IsOperator(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token, PredefinedType type);
bool IsPredefinedOperator(SyntaxToken token);
bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op);
/// <summary>
/// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a
/// identifier that is always treated as being a special keyword, regardless of where it is
/// found in the token stream. Examples of this are tokens like <see langword="class"/> and
/// <see langword="Class"/> in C# and VB respectively.
///
/// Importantly, this does *not* include contextual keywords. If contextual keywords are
/// important for your scenario, use <see cref="IsContextualKeyword"/> or <see
/// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using
/// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know
/// if this is effectively any identifier in the language, regardless of whether the language
/// is treating it as a keyword or not.
/// </summary>
bool IsReservedKeyword(SyntaxToken token);
/// <summary>
/// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A
/// 'contextual' keyword is a identifier that is only treated as being a special keyword in
/// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a
/// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see
/// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not*
/// 'contextual' keywords. This is because they are not treated as keywords depending on
/// the syntactic context around them. Instead, the language always treats them identifiers
/// that have special *semantic* meaning if they end up not binding to an existing symbol.
///
/// Importantly, if <paramref name="token"/> is not in the syntactic construct where the
/// language thinks an identifier should be contextually treated as a keyword, then this
/// will return <see langword="false"/>.
///
/// Or, in other words, the parser must be able to identify these cases in order to be a
/// contextual keyword. If identification happens afterwards, it's not contextual.
/// </summary>
bool IsContextualKeyword(SyntaxToken token);
/// <summary>
/// The set of identifiers that have special meaning directly after the `#` token in a
/// preprocessor directive. For example `if` or `pragma`.
/// </summary>
bool IsPreprocessorKeyword(SyntaxToken token);
bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
bool IsLiteral(SyntaxToken token);
bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token);
bool IsNumericLiteral(SyntaxToken token);
bool IsVerbatimStringLiteral(SyntaxToken token);
bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent);
bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent);
bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaration(SyntaxNode node);
bool IsTypeDeclaration(SyntaxNode node);
bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsRegularComment(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxTrivia trivia);
bool IsElastic(SyntaxTrivia trivia);
bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes);
bool IsSingleLineCommentTrivia(SyntaxTrivia trivia);
bool IsMultiLineCommentTrivia(SyntaxTrivia trivia);
bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia);
bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia);
bool IsShebangDirectiveTrivia(SyntaxTrivia trivia);
bool IsPreprocessorDirective(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxNode node);
string GetText(int kind);
bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken);
bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type);
bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op);
bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info);
bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode;
void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken);
bool IsVerbatimInterpolatedStringExpression(SyntaxNode node);
// Left side of = assignment.
bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement);
void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
// Left side of any assignment (for example = or ??= or *= or += )
bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node);
// Left side of compound assignment (for example ??= or *= or += )
bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node);
bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightSideOfDot(SyntaxNode? node);
/// <summary>
/// Get the node on the left side of the dot if given a dotted expression.
/// </summary>
/// <param name="allowImplicitTarget">
/// In VB, we have a member access expression with a null expression, this may be one of the
/// following forms:
/// 1) new With { .a = 1, .b = .a .a refers to the anonymous type
/// 2) With obj : .m .m refers to the obj type
/// 3) new T() With { .a = 1, .b = .a 'a refers to the T type
/// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null.
/// This parameter has no affect on C# node.
/// </param>
SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false);
bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
[return: NotNullIfNotNull("node")]
SyntaxNode? GetStandaloneExpression(SyntaxNode? node);
/// <summary>
/// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works
/// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in
/// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of
/// a conditional access, and commonly represents the full standalone expression that can be operated on
/// atomically.
/// </summary>
SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node);
/// <summary>
/// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/>
/// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/>
/// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed
/// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this
/// may return the expression in the surrounding With-statement.
/// </summary>
SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false);
SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node);
SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node);
bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetDefaultOfParameter(SyntaxNode node);
SyntaxNode? GetParameterList(SyntaxNode node);
bool IsParameterList([NotNullWhen(true)] SyntaxNode? node);
bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia);
void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList);
SyntaxNode GetExpressionOfArgument(SyntaxNode node);
SyntaxNode GetExpressionOfInterpolation(SyntaxNode node);
SyntaxNode GetNameOfAttribute(SyntaxNode node);
bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken GetIdentifierOfGenericName(SyntaxNode node);
SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node);
SyntaxToken GetIdentifierOfParameter(SyntaxNode node);
SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node);
SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node);
SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node);
SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node);
/// <summary>
/// True if this is an argument with just an expression and nothing else (i.e. no ref/out,
/// no named params, no omitted args).
/// </summary>
bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsArgument([NotNullWhen(true)] SyntaxNode? node);
RefKind GetRefKindOfArgument(SyntaxNode node);
void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity);
bool LooksGeneric(SyntaxNode simpleName);
SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node);
bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node);
bool IsAttributeName(SyntaxNode node);
// Violation. Doesn't correspond to any shared structure for vb/c#
SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node);
bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance);
bool IsDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Returns true for nodes that represent the body of a method.
///
/// For VB this will be
/// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator
/// bodies as well as accessor bodies. It will not be true for things like sub() function()
/// lambdas.
///
/// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a
/// method/constructor/deconstructor/operator/accessor. It will not be included for local
/// functions.
/// </summary>
bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement);
SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node);
SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node);
bool IsThisConstructorInitializer(SyntaxToken token);
bool IsBaseConstructorInitializer(SyntaxToken token);
bool IsQueryKeyword(SyntaxToken token);
bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node);
bool IsIdentifierStartCharacter(char c);
bool IsIdentifierPartCharacter(char c);
bool IsIdentifierEscapeCharacter(char c);
bool IsStartOfUnicodeEscapeSequence(char c);
bool IsValidIdentifier(string identifier);
bool IsVerbatimIdentifier(string identifier);
/// <summary>
/// Returns true if the given character is a character which may be included in an
/// identifier to specify the type of a variable.
/// </summary>
bool IsTypeCharacter(char c);
// Violation. This is a feature level API for QuickInfo.
bool IsBindableToken(SyntaxToken token);
bool IsInStaticContext(SyntaxNode node);
bool IsUnsafeContext(SyntaxNode node);
bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstructor(SyntaxNode node);
bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node);
bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node);
bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax.
/// </summary>
bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax.
/// In VB, this includes all block statements such as a MultiLineIfBlockSyntax.
/// </summary>
bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node);
// Violation. This should return a SyntaxList
IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node);
// Violation. This is a feature level API.
SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes);
/// <summary>
/// A node that can host a list of statements or a single statement. In addition to
/// every "executable block", this also includes C# embedded statement owners.
/// </summary>
// Violation. This is a feature level API.
bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node);
// Violation. This is a feature level API.
IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node);
bool AreEquivalent(SyntaxToken token1, SyntaxToken token2);
bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2);
string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null);
// Violation. This is a feature level API. How 'position' relates to 'containment' is not defined.
SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position);
SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true);
SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
SyntaxNode? WalkDownParentheses(SyntaxNode? node);
// Violation. This is a feature level API.
[return: NotNullIfNotNull("node")]
SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false);
// Violation. This is a feature level API.
List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root);
// Violation. This is a feature level API.
List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root);
SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration);
// Violation. This is a feature level API.
bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span);
// Violation. This is a feature level API.
TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body
/// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be
/// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns
/// an empty <see cref="TextSpan"/> at position 0.
/// </summary>
// Violation. This is a feature level API.
TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node);
/// <summary>
/// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find
/// All References. For example, if the token is part of the type of an object creation, the parenting object
/// creation expression is returned so that binding will return constructor symbols.
/// </summary>
// Violation. This is a feature level API.
SyntaxNode? TryGetBindableParent(SyntaxToken token);
// Violation. This is a feature level API.
IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken);
// Violation. This is a feature level API.
bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of
/// that arguments name.
/// </summary>
// Violation. This is a feature level API.
string GetNameForArgument(SyntaxNode? argument);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of
/// that arguments name.
/// </summary>
// Violation. This is a feature level API.
string GetNameForAttributeArgument(SyntaxNode? argument);
bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node);
bool IsPropertyPatternClause(SyntaxNode node);
bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node);
SyntaxNode GetTypeOfTypePattern(SyntaxNode node);
void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen);
void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation);
void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation);
void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern);
// Violation. This is a feature level API.
SyntaxNode? GetNextExecutableStatement(SyntaxNode statement);
bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken);
bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken);
SyntaxTokenList GetModifiers(SyntaxNode? node);
// Violation. WithXXX methods should not be here, but should be in SyntaxGenerator.
[return: NotNullIfNotNull("node")]
SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers);
// Violation. This is a feature level API.
Location GetDeconstructionReferenceLocation(SyntaxNode node);
// Violation. This is a feature level API.
SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token);
bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes);
bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node);
SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
#region IsXXX members
bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node);
#endregion
#region GetPartsOfXXX members
void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members);
void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression);
void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members);
void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull);
void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse);
void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList);
void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right);
void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name);
void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer);
void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen);
void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand);
void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right);
void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name);
#endregion
#region GetXXXOfYYYMembers
// note: this is only for nodes that have a single child nodes. If a node has multiple child nodes, then
// ISyntaxFacts should have a GetPartsOfXXX helper instead, and GetXXXOfYYY should be built off of that
// inside ISyntaxFactsExtensions
SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node);
SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node);
SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node);
SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node);
SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node);
#endregion
}
[Flags]
internal enum DisplayNameOptions
{
None = 0,
IncludeMemberKeyword = 1,
IncludeNamespaces = 1 << 1,
IncludeParameters = 1 << 2,
IncludeType = 1 << 3,
IncludeTypeParameters = 1 << 4
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
/// <summary>
/// Contains helpers to allow features and other algorithms to run over C# and Visual Basic code in a uniform fashion.
/// It should be thought of a generalized way to apply type-pattern-matching and syntax-deconstruction in a uniform
/// fashion over the languages. Helpers in this type should only be one of the following forms:
/// <list type="bullet">
/// <item>
/// 'IsXXX' where 'XXX' exactly matches one of the same named syntax (node, token, trivia, list, etc.) constructs that
/// both C# and VB have. For example 'IsSimpleName' to correspond to C# and VB's SimpleNameSyntax node. These 'checking'
/// methods should never fail. For non leaf node types this should be implemented as a typecheck ('is' in C#, 'typeof ... is'
/// in VB). For leaf nodes, this should be implemented by deffering to <see cref="ISyntaxKinds"/> to check against the
/// raw kind of the node.
/// </item>
/// <item>
/// 'GetPartsOfXXX(SyntaxNode node, out SyntaxNode/SyntaxToken part1, ...)' where 'XXX' one of the same named Syntax constructs
/// that both C# and VB have, and where the returned parts correspond to the members those nodes have in common across the
/// languages. For example 'GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right)'
/// VB. These functions should throw if passed a node that the corresponding 'IsXXX' did not return <see langword="true"/> for.
/// For nodes that only have a single child, 'GetPartsOfXXX' is not not needed and can be replaced with the easier to use
/// 'GetXXXOfYYY' to get that single child.
/// </item>
/// <item>
/// 'GetXxxOfYYY' where 'XXX' matches the name of a property on a 'YYY' syntax construct that both C# and VB have. For
/// example 'GetExpressionOfMemberAccessExpression' corresponding to MemberAccessExpressionsyntax.Expression in both C# and
/// VB. These functions should throw if passed a node that the corresponding 'IsYYY' did not return <see langword="true"/> for.
/// For nodes that only have a single child, these functions can stay here. For nodes with multiple children, these should migrate
/// to <see cref="ISyntaxFactsExtensions"/> and be built off of 'GetPartsOfXXX'.
/// </item>
/// <item>
/// Absolutely trivial questions that relate to syntax and can be asked sensibly of each language. For example,
/// if certain constructs (like 'patterns') are supported in that language or not.
/// </item>
/// </list>
///
/// <para>Importantly, avoid:</para>
///
/// <list type="bullet">
/// <item>
/// Functions that attempt to blur the lines between similar constructs in the same language. For example, a QualifiedName
/// is not the same as a MemberAccessExpression (despite A.B being representable as either depending on context).
/// Features that need to handle both should make it clear that they are doing so, showing that they're doing the right
/// thing for the contexts each can arise in (for the above example in 'type' vs 'expression' contexts).
/// </item>
/// <item>
/// Functions which are effectively specific to a single feature are are just trying to find a place to place complex
/// feature logic in a place such that it can run over VB or C#. For example, a function to determine if a position
/// is on the 'header' of a node. a 'header' is a not a well defined syntax concept that can be trivially asked of
/// nodes in either language. It is an excapsulation of a feature (or set of features) level idea that should be in
/// its own dedicated service.
/// </item>
/// <item>
/// Functions that mutate or update syntax constructs for example 'WithXXX'. These should be on SyntaxGenerator or
/// some other feature specific service.
/// </item>
/// <item>
/// Functions that a single item when one language may allow for multiple. For example 'GetIdentifierOfVariableDeclarator'.
/// In VB a VariableDeclarator can itself have several names, so calling code must be written to check for that and handle
/// it apropriately. Functions like this make it seem like that doesn't need to be considered, easily allowing for bugs
/// to creep in.
/// </item>
/// <item>
/// Abbreviating or otherwise changing the names that C# and VB share here. For example use 'ObjectCreationExpression'
/// not 'ObjectCreation'. This prevents accidental duplication and keeps consistency with all members.
/// </item>
/// </list>
/// </summary>
/// <remarks>
/// Many helpers in this type currently violate the above 'dos' and 'do nots'. They should be removed and either
/// inlined directly into the feature that needs if (if only a single feature), or moved into a dedicated service
/// for that purpose if needed by multiple features.
/// </remarks>
internal interface ISyntaxFacts
{
bool IsCaseSensitive { get; }
StringComparer StringComparer { get; }
SyntaxTrivia ElasticMarker { get; }
SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
ISyntaxKinds SyntaxKinds { get; }
bool SupportsIndexingInitializer(ParseOptions options);
bool SupportsLocalFunctionDeclaration(ParseOptions options);
bool SupportsNotPattern(ParseOptions options);
bool SupportsRecord(ParseOptions options);
bool SupportsRecordStruct(ParseOptions options);
bool SupportsThrowExpression(ParseOptions options);
SyntaxToken ParseToken(string text);
SyntaxTriviaList ParseLeadingTrivia(string text);
string EscapeIdentifier(string identifier);
bool IsVerbatimIdentifier(SyntaxToken token);
bool IsOperator(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token, PredefinedType type);
bool IsPredefinedOperator(SyntaxToken token);
bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op);
/// <summary>
/// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a
/// identifier that is always treated as being a special keyword, regardless of where it is
/// found in the token stream. Examples of this are tokens like <see langword="class"/> and
/// <see langword="Class"/> in C# and VB respectively.
///
/// Importantly, this does *not* include contextual keywords. If contextual keywords are
/// important for your scenario, use <see cref="IsContextualKeyword"/> or <see
/// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using
/// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know
/// if this is effectively any identifier in the language, regardless of whether the language
/// is treating it as a keyword or not.
/// </summary>
bool IsReservedKeyword(SyntaxToken token);
/// <summary>
/// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A
/// 'contextual' keyword is a identifier that is only treated as being a special keyword in
/// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a
/// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see
/// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not*
/// 'contextual' keywords. This is because they are not treated as keywords depending on
/// the syntactic context around them. Instead, the language always treats them identifiers
/// that have special *semantic* meaning if they end up not binding to an existing symbol.
///
/// Importantly, if <paramref name="token"/> is not in the syntactic construct where the
/// language thinks an identifier should be contextually treated as a keyword, then this
/// will return <see langword="false"/>.
///
/// Or, in other words, the parser must be able to identify these cases in order to be a
/// contextual keyword. If identification happens afterwards, it's not contextual.
/// </summary>
bool IsContextualKeyword(SyntaxToken token);
/// <summary>
/// The set of identifiers that have special meaning directly after the `#` token in a
/// preprocessor directive. For example `if` or `pragma`.
/// </summary>
bool IsPreprocessorKeyword(SyntaxToken token);
bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
bool IsLiteral(SyntaxToken token);
bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token);
bool IsNumericLiteral(SyntaxToken token);
bool IsVerbatimStringLiteral(SyntaxToken token);
bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaration(SyntaxNode node);
bool IsTypeDeclaration(SyntaxNode node);
bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsRegularComment(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxTrivia trivia);
bool IsElastic(SyntaxTrivia trivia);
bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes);
bool IsSingleLineCommentTrivia(SyntaxTrivia trivia);
bool IsMultiLineCommentTrivia(SyntaxTrivia trivia);
bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia);
bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia);
bool IsShebangDirectiveTrivia(SyntaxTrivia trivia);
bool IsPreprocessorDirective(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxNode node);
string GetText(int kind);
bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken);
bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type);
bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op);
bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info);
bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode;
void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken);
bool IsVerbatimInterpolatedStringExpression(SyntaxNode node);
// Left side of = assignment.
bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement);
void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
// Left side of any assignment (for example = or ??= or *= or += )
bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node);
// Left side of compound assignment (for example ??= or *= or += )
bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetRightHandSideOfAssignment(SyntaxNode node);
bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightSideOfDot(SyntaxNode? node);
/// <summary>
/// Get the node on the left side of the dot if given a dotted expression.
/// </summary>
/// <param name="allowImplicitTarget">
/// In VB, we have a member access expression with a null expression, this may be one of the
/// following forms:
/// 1) new With { .a = 1, .b = .a .a refers to the anonymous type
/// 2) With obj : .m .m refers to the obj type
/// 3) new T() With { .a = 1, .b = .a 'a refers to the T type
/// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null.
/// This parameter has no affect on C# node.
/// </param>
SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false);
bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
[return: NotNullIfNotNull("node")]
SyntaxNode? GetStandaloneExpression(SyntaxNode? node);
/// <summary>
/// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works
/// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in
/// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of
/// a conditional access, and commonly represents the full standalone expression that can be operated on
/// atomically.
/// </summary>
SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node);
/// <summary>
/// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/>
/// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/>
/// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed
/// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this
/// may return the expression in the surrounding With-statement.
/// </summary>
SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode node, bool allowImplicitTarget = false);
SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node);
SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node);
bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetDefaultOfParameter(SyntaxNode node);
SyntaxNode? GetParameterList(SyntaxNode node);
bool IsParameterList([NotNullWhen(true)] SyntaxNode? node);
bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia);
void GetPartsOfElementAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList);
SyntaxNode GetExpressionOfArgument(SyntaxNode node);
SyntaxNode GetExpressionOfInterpolation(SyntaxNode node);
SyntaxNode GetNameOfAttribute(SyntaxNode node);
bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken GetIdentifierOfGenericName(SyntaxNode node);
SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node);
SyntaxToken GetIdentifierOfParameter(SyntaxNode node);
SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node);
SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node);
SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node);
SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node);
/// <summary>
/// True if this is an argument with just an expression and nothing else (i.e. no ref/out,
/// no named params, no omitted args).
/// </summary>
bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsArgument([NotNullWhen(true)] SyntaxNode? node);
RefKind GetRefKindOfArgument(SyntaxNode node);
void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity);
bool LooksGeneric(SyntaxNode simpleName);
SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode node);
bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node);
bool IsAttributeName(SyntaxNode node);
// Violation. Doesn't correspond to any shared structure for vb/c#
SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node);
bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance);
bool IsDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Returns true for nodes that represent the body of a method.
///
/// For VB this will be
/// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator
/// bodies as well as accessor bodies. It will not be true for things like sub() function()
/// lambdas.
///
/// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a
/// method/constructor/deconstructor/operator/accessor. It will not be included for local
/// functions.
/// </summary>
bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement);
SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node);
SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node);
bool IsThisConstructorInitializer(SyntaxToken token);
bool IsBaseConstructorInitializer(SyntaxToken token);
bool IsQueryKeyword(SyntaxToken token);
bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node);
bool IsIdentifierStartCharacter(char c);
bool IsIdentifierPartCharacter(char c);
bool IsIdentifierEscapeCharacter(char c);
bool IsStartOfUnicodeEscapeSequence(char c);
bool IsValidIdentifier(string identifier);
bool IsVerbatimIdentifier(string identifier);
/// <summary>
/// Returns true if the given character is a character which may be included in an
/// identifier to specify the type of a variable.
/// </summary>
bool IsTypeCharacter(char c);
// Violation. This is a feature level API for QuickInfo.
bool IsBindableToken(SyntaxToken token);
bool IsInStaticContext(SyntaxNode node);
bool IsUnsafeContext(SyntaxNode node);
bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstructor(SyntaxNode node);
bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node);
bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node);
bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax.
/// </summary>
bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax.
/// In VB, this includes all block statements such as a MultiLineIfBlockSyntax.
/// </summary>
bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node);
// Violation. This should return a SyntaxList
IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node);
// Violation. This is a feature level API.
SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes);
/// <summary>
/// A node that can host a list of statements or a single statement. In addition to
/// every "executable block", this also includes C# embedded statement owners.
/// </summary>
// Violation. This is a feature level API.
bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node);
// Violation. This is a feature level API.
IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node);
bool AreEquivalent(SyntaxToken token1, SyntaxToken token2);
bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2);
string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null);
// Violation. This is a feature level API. How 'position' relates to 'containment' is not defined.
SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position);
SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true);
SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
SyntaxNode? WalkDownParentheses(SyntaxNode? node);
// Violation. This is a feature level API.
[return: NotNullIfNotNull("node")]
SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false);
// Violation. This is a feature level API.
List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root);
// Violation. This is a feature level API.
List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root);
SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration);
// Violation. This is a feature level API.
bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span);
// Violation. This is a feature level API.
TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body
/// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be
/// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns
/// an empty <see cref="TextSpan"/> at position 0.
/// </summary>
// Violation. This is a feature level API.
TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node);
/// <summary>
/// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find
/// All References. For example, if the token is part of the type of an object creation, the parenting object
/// creation expression is returned so that binding will return constructor symbols.
/// </summary>
// Violation. This is a feature level API.
SyntaxNode? TryGetBindableParent(SyntaxToken token);
// Violation. This is a feature level API.
IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken);
// Violation. This is a feature level API.
bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of
/// that arguments name.
/// </summary>
// Violation. This is a feature level API.
string GetNameForArgument(SyntaxNode? argument);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of
/// that arguments name.
/// </summary>
// Violation. This is a feature level API.
string GetNameForAttributeArgument(SyntaxNode? argument);
bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node);
bool IsPropertyPatternClause(SyntaxNode node);
bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node);
SyntaxNode GetTypeOfTypePattern(SyntaxNode node);
void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen);
void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation);
void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation);
void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern);
bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken);
bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken);
SyntaxTokenList GetModifiers(SyntaxNode? node);
// Violation. WithXXX methods should not be here, but should be in SyntaxGenerator.
[return: NotNullIfNotNull("node")]
SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers);
// Violation. This is a feature level API.
Location GetDeconstructionReferenceLocation(SyntaxNode node);
// Violation. This is a feature level API.
SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token);
bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes);
bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node);
SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
#region IsXXX members
bool IsAnonymousFunctionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleName([NotNullWhen(true)] SyntaxNode? node);
#endregion
#region GetPartsOfXXX members
void GetPartsOfBaseNamespaceDeclaration(SyntaxNode node, out SyntaxNode name, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> members);
void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression);
void GetPartsOfCompilationUnit(SyntaxNode node, out SyntaxList<SyntaxNode> imports, out SyntaxList<SyntaxNode> attributeLists, out SyntaxList<SyntaxNode> members);
void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull);
void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse);
void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode? argumentList);
void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right);
void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name);
void GetPartsOfObjectCreationExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode? argumentList, out SyntaxNode? initializer);
void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen);
void GetPartsOfPrefixUnaryExpression(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode operand);
void GetPartsOfQualifiedName(SyntaxNode node, out SyntaxNode left, out SyntaxToken dotToken, out SyntaxNode right);
void GetPartsOfUsingAliasDirective(SyntaxNode node, out SyntaxToken globalKeyword, out SyntaxToken alias, out SyntaxNode name);
#endregion
#region GetXXXOfYYYMembers
// note: this is only for nodes that have a single child nodes. If a node has multiple child nodes, then
// ISyntaxFacts should have a GetPartsOfXXX helper instead, and GetXXXOfYYY should be built off of that
// inside ISyntaxFactsExtensions
SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node);
SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node);
SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode node);
SyntaxNode GetExpressionOfThrowExpression(SyntaxNode node);
SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node);
#endregion
}
[Flags]
internal enum DisplayNameOptions
{
None = 0,
IncludeMemberKeyword = 1,
IncludeNamespaces = 1 << 1,
IncludeParameters = 1 << 2,
IncludeType = 1 << 3,
IncludeTypeParameters = 1 << 4
}
}
| 1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxFacts.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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports System.Diagnostics.CodeAnalysis
#If CODE_STYLE Then
Imports Microsoft.CodeAnalysis.Internal.Editing
#Else
Imports Microsoft.CodeAnalysis.Editing
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Friend Class VisualBasicSyntaxFacts
Inherits AbstractSyntaxFacts
Implements ISyntaxFacts
Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts
Protected Sub New()
End Sub
Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive
Get
Return False
End Get
End Property
Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer
Get
Return CaseInsensitiveComparison.Comparer
End Get
End Property
Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker
Get
Return SyntaxFactory.ElasticMarker
End Get
End Property
Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed
Get
Return SyntaxFactory.ElasticCarriageReturnLineFeed
End Get
End Property
Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds
Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer
Return False
End Function
Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression
Return False
End Function
Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration
Return False
End Function
Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord
Return False
End Function
Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct
Return False
End Function
Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken
Return SyntaxFactory.ParseToken(text, startStatement:=True)
End Function
Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia
Return SyntaxFactory.ParseLeadingTrivia(text)
End Function
Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier
Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier)
Dim needsEscaping = keywordKind <> SyntaxKind.None
Return If(needsEscaping, "[" & identifier & "]", identifier)
End Function
Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return False
End Function
Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator
Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse
(IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax))
End Function
Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword
Return token.IsContextualKeyword()
End Function
Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword
Return token.IsReservedKeyword()
End Function
Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword
Return token.IsPreprocessorKeyword()
End Function
Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext
Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)
End Function
Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace
If token.Kind = SyntaxKind.CloseBraceToken Then
Dim tuples = token.Parent.GetBraces()
openBrace = tuples.openBrace
Return openBrace.Kind = SyntaxKind.OpenBraceToken
End If
Return False
End Function
Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken)
End Function
Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective
Return TypeOf node Is DirectiveTriviaSyntax
End Function
Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo
Select Case node.Kind
Case SyntaxKind.ExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False)
Return True
Case SyntaxKind.EndExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(Nothing, True)
Return True
End Select
Return False
End Function
Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression
' VB doesn't support declaration expressions
Return False
End Function
Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName
Return node.IsParentKind(SyntaxKind.Attribute) AndAlso
DirectCast(node.Parent, AttributeSyntax).Name Is node
End Function
Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression
Dim vbNode = TryCast(node, ExpressionSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName()
End Function
Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression
Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax)
Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node
End Function
Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression
Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax))
End Function
Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression
Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression()
End Function
Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument
Dim arg = TryCast(node, SimpleArgumentSyntax)
Return arg?.NameColonEquals IsNot Nothing
End Function
Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument
Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node)
End Function
Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter
Return DirectCast(node, ParameterSyntax).Identifier?.Identifier
End Function
Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter
Return DirectCast(node, ParameterSyntax).Default
End Function
Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList
Return node.GetParameterList()
End Function
Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList
Return node.IsKind(SyntaxKind.ParameterList)
End Function
Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember
Return HasIncompleteParentMember(node)
End Function
Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName
Return DirectCast(genericName, GenericNameSyntax).Identifier
End Function
Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName
Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso
DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node
End Function
Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment
Return False
End Function
Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement
Return False
End Function
Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement
Return TypeOf node Is StatementSyntax
End Function
Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement
Return TypeOf node Is ExecutableStatementSyntax
End Function
Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody
Return TypeOf node Is MethodBlockBaseSyntax
End Function
Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement
Return DirectCast(node, ReturnStatementSyntax).Expression
End Function
Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsThisConstructorInitializer()
End If
Return False
End Function
Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsBaseConstructorInitializer()
End If
Return False
End Function
Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword
Select Case token.Kind()
Case _
SyntaxKind.JoinKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.AggregateKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.SelectKeyword
Return TypeOf token.Parent Is QueryClauseSyntax
Case SyntaxKind.GroupKeyword
Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation))
Case SyntaxKind.EqualsKeyword
Return TypeOf token.Parent Is JoinConditionSyntax
Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword
Return TypeOf token.Parent Is OrderingSyntax
Case SyntaxKind.InKeyword
Return TypeOf token.Parent Is CollectionRangeVariableSyntax
Case Else
Return False
End Select
End Function
Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None
End Function
Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType = type
End Function
Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType
type = GetPredefinedType(token)
Return type <> PredefinedType.None
End Function
Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType
Select Case token.Kind
Case SyntaxKind.BooleanKeyword
Return PredefinedType.Boolean
Case SyntaxKind.ByteKeyword
Return PredefinedType.Byte
Case SyntaxKind.SByteKeyword
Return PredefinedType.SByte
Case SyntaxKind.IntegerKeyword
Return PredefinedType.Int32
Case SyntaxKind.UIntegerKeyword
Return PredefinedType.UInt32
Case SyntaxKind.ShortKeyword
Return PredefinedType.Int16
Case SyntaxKind.UShortKeyword
Return PredefinedType.UInt16
Case SyntaxKind.LongKeyword
Return PredefinedType.Int64
Case SyntaxKind.ULongKeyword
Return PredefinedType.UInt64
Case SyntaxKind.SingleKeyword
Return PredefinedType.Single
Case SyntaxKind.DoubleKeyword
Return PredefinedType.Double
Case SyntaxKind.DecimalKeyword
Return PredefinedType.Decimal
Case SyntaxKind.StringKeyword
Return PredefinedType.String
Case SyntaxKind.CharKeyword
Return PredefinedType.Char
Case SyntaxKind.ObjectKeyword
Return PredefinedType.Object
Case SyntaxKind.DateKeyword
Return PredefinedType.DateTime
Case Else
Return PredefinedType.None
End Select
End Function
Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None
End Function
Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op
End Function
Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator
op = GetPredefinedOperator(token)
Return op <> PredefinedOperator.None
End Function
Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator
Select Case token.Kind
Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken
Return PredefinedOperator.Addition
Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken
Return PredefinedOperator.Subtraction
Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword
Return PredefinedOperator.BitwiseAnd
Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword
Return PredefinedOperator.BitwiseOr
Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken
Return PredefinedOperator.Concatenate
Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken
Return PredefinedOperator.Division
Case SyntaxKind.EqualsToken
Return PredefinedOperator.Equality
Case SyntaxKind.XorKeyword
Return PredefinedOperator.ExclusiveOr
Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken
Return PredefinedOperator.Exponent
Case SyntaxKind.GreaterThanToken
Return PredefinedOperator.GreaterThan
Case SyntaxKind.GreaterThanEqualsToken
Return PredefinedOperator.GreaterThanOrEqual
Case SyntaxKind.LessThanGreaterThanToken
Return PredefinedOperator.Inequality
Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken
Return PredefinedOperator.IntegerDivision
Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken
Return PredefinedOperator.LeftShift
Case SyntaxKind.LessThanToken
Return PredefinedOperator.LessThan
Case SyntaxKind.LessThanEqualsToken
Return PredefinedOperator.LessThanOrEqual
Case SyntaxKind.LikeKeyword
Return PredefinedOperator.Like
Case SyntaxKind.NotKeyword
Return PredefinedOperator.Complement
Case SyntaxKind.ModKeyword
Return PredefinedOperator.Modulus
Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken
Return PredefinedOperator.Multiplication
Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken
Return PredefinedOperator.RightShift
Case Else
Return PredefinedOperator.None
End Select
End Function
Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText
Return SyntaxFacts.GetText(CType(kind, SyntaxKind))
End Function
Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter
Return SyntaxFacts.IsIdentifierPartCharacter(c)
End Function
Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter
Return SyntaxFacts.IsIdentifierStartCharacter(c)
End Function
Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter
Return c = "["c OrElse c = "]"c
End Function
Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier
Dim token = SyntaxFactory.ParseToken(identifier)
' TODO: There is no way to get the diagnostics to see if any are actually errors?
Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length
End Function
Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]"
End Function
Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter
Return c = "%"c OrElse
c = "&"c OrElse
c = "@"c OrElse
c = "!"c OrElse
c = "#"c OrElse
c = "$"c
End Function
Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence
Return False ' VB does not support identifiers with escaped unicode characters
End Function
Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral
Select Case token.Kind()
Case _
SyntaxKind.IntegerLiteralToken,
SyntaxKind.CharacterLiteralToken,
SyntaxKind.DecimalLiteralToken,
SyntaxKind.FloatingLiteralToken,
SyntaxKind.DateLiteralToken,
SyntaxKind.StringLiteralToken,
SyntaxKind.DollarSignDoubleQuoteToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.InterpolatedStringTextToken,
SyntaxKind.TrueKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.NothingKeyword
Return True
End Select
Return False
End Function
Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral
Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken)
End Function
Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken
Return Me.IsWord(token) OrElse
Me.IsLiteral(token) OrElse
Me.IsOperator(token)
End Function
Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression
Return False
End Function
Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName
Dim simpleName = DirectCast(node, SimpleNameSyntax)
name = simpleName.Identifier.ValueText
arity = simpleName.Arity
End Sub
Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric
Return name.IsKind(SyntaxKind.GenericName)
End Function
Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression
Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)
End Function
Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding
' Member bindings are a C# concept.
Return Nothing
End Function
Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression
' Member bindings are a C# concept.
Return Nothing
End Function
Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression
Dim invocation = TryCast(node, InvocationExpressionSyntax)
If invocation IsNot Nothing Then
expression = invocation?.Expression
argumentList = invocation?.ArgumentList
Return
End If
If node.Kind() = SyntaxKind.DictionaryAccessExpression Then
GetPartsOfMemberAccessExpression(node, expression, argumentList)
Return
End If
Throw ExceptionUtilities.UnexpectedValue(node.Kind())
End Sub
Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation
Return DirectCast(node, InterpolationSyntax).Expression
End Function
Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext
Return SyntaxFacts.IsInNamespaceOrTypeContext(node)
End Function
Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList
Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing
End Function
Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext
Return node.IsInStaticContext()
End Function
Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument
Return DirectCast(node, ArgumentSyntax).GetArgumentExpression()
End Function
Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument
' TODO(cyrusn): Consider the method this argument is passed to, to determine this.
Return RefKind.None
End Function
Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument
Return TypeOf node Is ArgumentSyntax
End Function
Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument
Dim argument = TryCast(node, ArgumentSyntax)
Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted
End Function
Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext
Return node.IsInConstantContext()
End Function
Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor
Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock)
End Function
Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext
Return False
End Function
Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute
Return DirectCast(node, AttributeSyntax).Name
End Function
Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier
Dim identifierName = TryCast(node, IdentifierNameSyntax)
Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso
identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso
identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso
identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute)
End Function
Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration
If root Is Nothing Then
Throw New ArgumentNullException(NameOf(root))
End If
If position < 0 OrElse position > root.Span.End Then
Throw New ArgumentOutOfRangeException(NameOf(position))
End If
Return root.
FindToken(position).
GetAncestors(Of SyntaxNode)().
FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax)
End Function
Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim parent = node.Parent
While node IsNot Nothing
If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then
Return node
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim unused As SyntaxNode = Nothing
Return IsMemberInitializerNamedAssignmentIdentifier(node, unused)
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(
node As SyntaxNode,
ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
' .parent is the NamedField.
' .parent.parent is the ObjectInitializer.
' .parent.parent.parent will be the ObjectCreationExpression.
initializedInstance = identifier.Parent.Parent.Parent
Return True
End If
Return False
End Function
Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern
Return False
End Function
Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause
Return False
End Function
Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression
' VB doesn't have a specialized node for element access. Instead, it just uses an
' invocation expression or dictionary access expression.
Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression
End Function
Public Function IsTypeNamedVarInVariableOrFieldDeclaration(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedVarInVariableOrFieldDeclaration
Return False
End Function
Public Function IsTypeNamedDynamic(token As SyntaxToken, parent As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeNamedDynamic
Return False
End Function
Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef
Return False
End Function
Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration
Contract.ThrowIfNull(root, NameOf(root))
Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position))
Dim [end] = root.FullSpan.End
If [end] = 0 Then
' empty file
Return Nothing
End If
' make sure position doesn't touch end of root
position = Math.Min(position, [end] - 1)
Dim node = root.FindToken(position).Parent
While node IsNot Nothing
If useFullSpan OrElse node.Span.Contains(position) Then
If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return node
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return node
End If
If TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is FieldDeclarationSyntax Then
Return node
End If
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember
' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and
' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things
' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level
' members.
If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return True
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return True
End If
If TypeOf node Is DeclareStatementSyntax Then
Return True
End If
Return TypeOf node Is ConstructorBlockSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is OperatorBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is FieldDeclarationSyntax
End Function
Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding
Dim member = GetContainingMemberDeclaration(node, node.SpanStart)
If member Is Nothing Then
Return Nothing
End If
' TODO: currently we only support method for now
Dim method = TryCast(member, MethodBlockBaseSyntax)
If method IsNot Nothing Then
If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then
Return Nothing
End If
' We don't want to include the BlockStatement or any trailing trivia up to and including its statement
' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up
' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start
' of the EndBlockStatements leading trivia.
Dim firstStatement = method.Statements.FirstOrDefault()
Dim spanStart = If(firstStatement IsNot Nothing,
firstStatement.FullSpan.Start,
method.EndBlockStatement.FullSpan.Start)
Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart)
End If
Return Nothing
End Function
Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span)
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span)
End If
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span)
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span)
End If
Return False
End Function
Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean
If innerSpan.IsEmpty Then
Return outerSpan.Contains(innerSpan.Start)
End If
Return outerSpan.Contains(innerSpan)
End Function
Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=True, methodLevel:=True)
Return list
End Function
Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=False, methodLevel:=True)
Return list
End Function
Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration
Return DirectCast(typeDeclaration, TypeBlockSyntax).Members
End Function
Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers
Return TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Private Const s_dotToken As String = "."
Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName
If node Is Nothing Then
Return String.Empty
End If
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
' member keyword (if any)
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then
Dim keywordToken = memberDeclaration.GetMemberKeywordToken()
If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then
builder.Append(keywordToken.Text)
builder.Append(" "c)
End If
End If
Dim names = ArrayBuilder(Of String).GetInstance()
' containing type(s)
Dim parent = node.Parent
While TypeOf parent Is TypeBlockSyntax
names.Push(GetName(parent, options, containsGlobalKeyword:=False))
parent = parent.Parent
End While
If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then
' containing namespace(s) in source (if any)
Dim containsGlobalKeyword As Boolean = False
While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock
names.Push(GetName(parent, options, containsGlobalKeyword))
parent = parent.Parent
End While
' root namespace (if any)
If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then
builder.Append(rootNamespace)
builder.Append(s_dotToken)
End If
End If
While Not names.IsEmpty()
Dim name = names.Pop()
If name IsNot Nothing Then
builder.Append(name)
builder.Append(s_dotToken)
End If
End While
names.Free()
' name (include generic type parameters)
builder.Append(GetName(node, options, containsGlobalKeyword:=False))
' parameter list (if any)
If (options And DisplayNameOptions.IncludeParameters) <> 0 Then
builder.Append(memberDeclaration.GetParameterList())
End If
' As clause (if any)
If (options And DisplayNameOptions.IncludeType) <> 0 Then
Dim asClause = memberDeclaration.GetAsClause()
If asClause IsNot Nothing Then
builder.Append(" "c)
builder.Append(asClause)
End If
End If
Return pooled.ToStringAndFree()
End Function
Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String
Const missingTokenPlaceholder As String = "?"
Select Case node.Kind()
Case SyntaxKind.CompilationUnit
Return Nothing
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier
Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text)
Case SyntaxKind.IncompleteMember
Return missingTokenPlaceholder
Case SyntaxKind.NamespaceBlock
Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name
If nameSyntax.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return Nothing
Else
Return GetName(nameSyntax, options, containsGlobalKeyword)
End If
Case SyntaxKind.QualifiedName
Dim qualified = CType(node, QualifiedNameSyntax)
If qualified.Left.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified
Else
Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword)
End If
End Select
Dim name As String = Nothing
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If memberDeclaration IsNot Nothing Then
Dim nameToken = memberDeclaration.GetNameToken()
If nameToken <> Nothing Then
name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text)
If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
builder.Append(name)
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList())
name = pooled.ToStringAndFree()
End If
End If
End If
Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString())
Return name
End Function
Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax)
If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then
builder.Append("(Of ")
builder.Append(typeParameterList.Parameters(0).Identifier.Text)
For i = 1 To typeParameterList.Parameters.Count - 1
builder.Append(", ")
builder.Append(typeParameterList.Parameters(i).Identifier.Text)
Next
builder.Append(")"c)
End If
End Sub
Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean)
Debug.Assert(topLevel OrElse methodLevel)
For Each member In node.GetMembers()
If IsTopLevelNodeWithMembers(member) Then
If topLevel Then
list.Add(member)
End If
AppendMembers(member, list, topLevel, methodLevel)
Continue For
End If
If methodLevel AndAlso IsMethodLevelMember(member) Then
list.Add(member)
End If
Next
End Sub
Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent
Dim node = token.Parent
While node IsNot Nothing
Dim parent = node.Parent
' If this node is on the left side of a member access expression, don't ascend
' further or we'll end up binding to something else.
Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
If memberAccess.Expression Is node Then
Exit While
End If
End If
' If this node is on the left side of a qualified name, don't ascend
' further or we'll end up binding to something else.
Dim qualifiedName = TryCast(parent, QualifiedNameSyntax)
If qualifiedName IsNot Nothing Then
If qualifiedName.Left Is node Then
Exit While
End If
End If
' If this node is the type of an object creation expression, return the
' object creation expression.
Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax)
If objectCreation IsNot Nothing Then
If objectCreation.Type Is node Then
node = parent
Exit While
End If
End If
' The inside of an interpolated string is treated as its own token so we
' need to force navigation to the parent expression syntax.
If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then
node = parent
Exit While
End If
' If this node is not parented by a name, we're done.
Dim name = TryCast(parent, NameSyntax)
If name Is Nothing Then
Exit While
End If
node = parent
End While
Return node
End Function
Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors
Dim compilationUnit = TryCast(root, CompilationUnitSyntax)
If compilationUnit Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim constructors = New List(Of SyntaxNode)()
AppendConstructors(compilationUnit.Members, constructors, cancellationToken)
Return constructors
End Function
Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken)
For Each member As StatementSyntax In members
cancellationToken.ThrowIfCancellationRequested()
Dim constructor = TryCast(member, ConstructorBlockSyntax)
If constructor IsNot Nothing Then
constructors.Add(constructor)
Continue For
End If
Dim [namespace] = TryCast(member, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
AppendConstructors([namespace].Members, constructors, cancellationToken)
End If
Dim [class] = TryCast(member, ClassBlockSyntax)
If [class] IsNot Nothing Then
AppendConstructors([class].Members, constructors, cancellationToken)
End If
Dim [struct] = TryCast(member, StructureBlockSyntax)
If [struct] IsNot Nothing Then
AppendConstructors([struct].Members, constructors, cancellationToken)
End If
Next
End Sub
Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition
Dim trivia = tree.FindTriviaToLeft(position, cancellationToken)
If trivia.Kind = SyntaxKind.DisabledTextTrivia Then
Return trivia.FullSpan
End If
Return Nothing
End Function
Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument
If TryCast(argument, ArgumentSyntax)?.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
End If
Return String.Empty
End Function
Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument
' All argument types are ArgumentSyntax in VB.
Return GetNameForArgument(argument)
End Function
Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot
Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot()
End Function
Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Right,
TryCast(node, MemberAccessExpressionSyntax)?.Name)
End Function
Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Left,
TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget))
End Function
Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier
Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing
End Function
Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement
End Function
Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement
End Function
Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement
End Function
Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment
Return DirectCast(node, AssignmentStatementSyntax).Right
End Function
Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator
Return node.IsKind(SyntaxKind.InferredFieldInitializer)
End Function
Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression
Return False
End Function
Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression
Return False
End Function
Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString
Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value
End Function
Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral
Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral
' VB does not have verbatim strings
Return False
End Function
Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression
Dim argumentList = DirectCast(node, InvocationExpressionSyntax).ArgumentList
Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList))
End Function
Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression
Dim argumentList = DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList
Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList))
End Function
Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList
Return DirectCast(node, ArgumentListSyntax).Arguments
End Function
Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine
Return node.ConvertToSingleLine(useElasticTrivia)
End Function
Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return node.IsKind(SyntaxKind.DocumentationCommentTrivia)
End Function
Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport
Return node.IsKind(SyntaxKind.ImportsStatement)
End Function
Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute
Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword)
End Function
Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute
Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword)
End Function
Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean
If node.IsKind(SyntaxKind.Attribute) Then
Dim attributeNode = CType(node, AttributeSyntax)
If attributeNode.Target IsNot Nothing Then
Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget)
End If
End If
Return False
End Function
Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration
' From the Visual Basic language spec:
' NamespaceMemberDeclaration :=
' NamespaceDeclaration |
' TypeDeclaration
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
' ClassMemberDeclaration ::=
' NonModuleDeclaration |
' EventMemberDeclaration |
' VariableMemberDeclaration |
' ConstantMemberDeclaration |
' MethodMemberDeclaration |
' PropertyMemberDeclaration |
' ConstructorMemberDeclaration |
' OperatorDeclaration
Select Case node.Kind()
' Because fields declarations can define multiple symbols "Public a, b As Integer"
' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
Case SyntaxKind.VariableDeclarator
If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then
Return True
End If
Return False
Case SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumStatement,
SyntaxKind.EnumBlock,
SyntaxKind.StructureStatement,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassStatement,
SyntaxKind.ClassBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EventStatement,
SyntaxKind.EventBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.FieldDeclaration,
SyntaxKind.SubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SubNewStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.OperatorBlock
Return True
End Select
Return False
End Function
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return True
End Select
Return False
End Function
Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement
Return node.IsKind(SyntaxKind.SimpleAssignmentStatement)
End Function
Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement
' VB only has assignment statements, so this can just delegate to that helper
GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right)
End Sub
Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement
Dim assignment = DirectCast(statement, AssignmentStatementSyntax)
left = assignment.Left
operatorToken = assignment.OperatorToken
right = assignment.Right
End Sub
Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName
Return DirectCast(node, SimpleNameSyntax).Identifier
End Function
Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier
End Function
Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter
Return DirectCast(node, ParameterSyntax).Identifier.Identifier
End Function
Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ClassStatement,
SyntaxKind.ModuleStatement
Return DirectCast(node, TypeStatementSyntax).Identifier
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(node, DelegateStatementSyntax).Identifier
End Select
Throw ExceptionUtilities.UnexpectedValue(node)
End Function
Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName
Return DirectCast(node, IdentifierNameSyntax).Identifier
End Function
Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement
Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators.
Contains(DirectCast(declarator, VariableDeclaratorSyntax))
End Function
Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(token1, token2)
End Function
Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(node1, node2)
End Function
Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach
Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node
End Function
Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement
Return DirectCast(node, ExpressionStatementSyntax).Expression
End Function
Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression
Return node.IsKind(SyntaxKind.TypeOfIsExpression)
End Function
Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses
Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node)
End Function
Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression
Dim tupleExpr = DirectCast(node, TupleExpressionSyntax)
openParen = tupleExpr.OpenParenToken
arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax))
closeParen = tupleExpr.CloseParenToken
End Sub
Public Function GetNextExecutableStatement(statement As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNextExecutableStatement
Return DirectCast(statement, StatementSyntax).GetNextStatement()?.FirstAncestorOrSelf(Of ExecutableStatementSyntax)
End Function
Private Function ISyntaxFacts_IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineCommentTrivia
Return MyBase.IsSingleLineCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineCommentTrivia
Return MyBase.IsMultiLineCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineDocCommentTrivia
Return MyBase.IsSingleLineDocCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineDocCommentTrivia
Return MyBase.IsMultiLineDocCommentTrivia(trivia)
Return False
End Function
Private Function ISyntaxFacts_IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsShebangDirectiveTrivia
Return MyBase.IsShebangDirectiveTrivia(trivia)
End Function
Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsPreprocessorDirective
Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind())
End Function
Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic
Return trivia.IsElastic()
End Function
Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective
Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes)
End Function
Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean
Return token.ContainsInterleavedDirective(span, cancellationToken)
End Function
Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return ContainsInterleavedDirective(node, cancellationToken)
End Function
Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return ContainsInterleavedDirective(nodes, cancellationToken)
End Function
Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia
Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia
End Function
Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers
Return node.GetModifiers()
End Function
Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers
Return node.WithModifiers(modifiers)
End Function
Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement
Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators
End Function
Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Initializer
End Function
Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type
End Function
Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause
Return DirectCast(node, EqualsValueSyntax).Value
End Function
Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock
' VB has no equivalent of curly braces.
Return False
End Function
Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock
Return node.IsExecutableBlock()
End Function
Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements
Return node.GetExecutableBlockStatements()
End Function
Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock
Return nodes.FindInnermostCommonExecutableBlock()
End Function
Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer
Return IsExecutableBlock(node)
End Function
Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements
Return GetExecutableBlockStatements(node)
End Function
Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression
Return node.Kind = SyntaxKind.CTypeExpression
End Function
Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression
Return node.Kind = SyntaxKind.DirectCastExpression
End Function
Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression
Dim cast = DirectCast(node, DirectCastExpressionSyntax)
type = cast.Type
expression = cast.Expression
End Sub
Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation
Throw New NotImplementedException()
End Function
Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride
If token.Kind() = SyntaxKind.OverridesKeyword Then
Dim parent = token.Parent
Select Case parent.Kind()
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(parent, MethodStatementSyntax)
Return method.Identifier
Case SyntaxKind.PropertyStatement
Dim [property] = DirectCast(parent, PropertyStatementSyntax)
Return [property].Identifier
End Select
End If
Return Nothing
End Function
Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective
Return MyBase.SpansPreprocessorDirective(nodes)
End Function
Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean
Return MyBase.SpansPreprocessorDirective(tokens)
End Function
Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression
' Does not exist in VB.
Return False
End Function
Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists
Return node.GetAttributeLists()
End Function
Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective
Dim importStatement = TryCast(node, ImportsStatementSyntax)
If (importStatement IsNot Nothing) Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
Return True
End If
End If
Next
End If
Return False
End Function
Public Sub GetPartsOfUsingAliasDirective(
node As SyntaxNode,
ByRef globalKeyword As SyntaxToken,
ByRef [alias] As SyntaxToken,
ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUsingAliasDirective
Dim importStatement = DirectCast(node, ImportsStatementSyntax)
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
globalKeyword = Nothing
[alias] = simpleImportsClause.Alias.Identifier
name = simpleImportsClause.Name
Return
End If
End If
Next
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax
Dim xmlElement = TryCast(node, XmlElementSyntax)
If xmlElement IsNot Nothing Then
Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax)
Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName
End If
Return False
End Function
Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax
Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax)
If documentationCommentTrivia IsNot Nothing Then
Return documentationCommentTrivia.Content
End If
Return Nothing
End Function
Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind)
End Function
Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean
Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement)
End Function
Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer
Dim count As Integer = 0
For i = 0 To nodes.Count - 1
count = count + GetDeclarationCount(nodes(i))
Next
Return count
End Function
Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer
Select Case node.Kind
Case SyntaxKind.FieldDeclaration
Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators)
Case SyntaxKind.LocalDeclarationStatement
Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators)
Case SyntaxKind.VariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Count
Case SyntaxKind.AttributesStatement
Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists)
Case SyntaxKind.AttributeList
Return DirectCast(node, AttributeListSyntax).Attributes.Count
Case SyntaxKind.ImportsStatement
Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count
End Select
Return 1
End Function
Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern
Return False
End Function
Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression
Return False
End Function
Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern
Return False
End Function
Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern
Return False
End Function
Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern
Return False
End Function
Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern
Return False
End Function
Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern
Return False
End Function
Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern
Return False
End Function
Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern
Return False
End Function
Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern
Return False
End Function
Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern
Return False
End Function
Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern
Return False
End Function
Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern
Return False
End Function
Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern
Return False
End Function
Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression
Throw ExceptionUtilities.Unreachable
End Sub
Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern
Throw ExceptionUtilities.Unreachable
End Function
Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern
Throw New NotImplementedException()
End Sub
Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern
Throw New NotImplementedException()
End Sub
Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern
Throw New NotImplementedException()
End Function
Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression
Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax)
stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken
contents = interpolatedStringExpressionSyntax.Contents
stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken
End Sub
Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression
Return False
End Function
#Region "IsXXX members"
Public Function IsAnonymousFunctionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunctionExpression
Return TypeOf node Is LambdaExpressionSyntax
End Function
Public Function IsBaseNamespaceDeclaration(<NotNullWhen(True)> node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseNamespaceDeclaration
Return TypeOf node Is NamespaceBlockSyntax
End Function
Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression
Return TypeOf node Is BinaryExpressionSyntax
End Function
Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression
Return TypeOf node Is LiteralExpressionSyntax
End Function
Public Function IsMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberAccessExpression
Return TypeOf node Is MemberAccessExpressionSyntax
End Function
Public Function IsSimpleName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleName
Return TypeOf node Is SimpleNameSyntax
End Function
#End Region
#Region "GetPartsOfXXX members"
Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression
Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax)
left = binaryExpression.Left
operatorToken = binaryExpression.OperatorToken
right = binaryExpression.Right
End Sub
Public Sub GetPartsOfCompilationUnit(node As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef attributeLists As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfCompilationUnit
Dim compilationUnit = DirectCast(node, CompilationUnitSyntax)
[imports] = compilationUnit.Imports
attributeLists = compilationUnit.Attributes
members = compilationUnit.Members
End Sub
Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression
Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax)
expression = conditionalAccess.Expression
operatorToken = conditionalAccess.QuestionMarkToken
whenNotNull = conditionalAccess.WhenNotNull
End Sub
Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression
Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax)
condition = conditionalExpression.Condition
whenTrue = conditionalExpression.WhenTrue
whenFalse = conditionalExpression.WhenFalse
End Sub
Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression
Dim invocation = DirectCast(node, InvocationExpressionSyntax)
expression = invocation.Expression
argumentList = invocation.ArgumentList
End Sub
Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression
Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax)
expression = memberAccess.Expression
operatorToken = memberAccess.OperatorToken
name = memberAccess.Name
End Sub
Public Sub GetPartsOfBaseNamespaceDeclaration(node As SyntaxNode, ByRef name As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfBaseNamespaceDeclaration
Dim namespaceBlock = DirectCast(node, NamespaceBlockSyntax)
name = namespaceBlock.NamespaceStatement.Name
[imports] = Nothing
members = namespaceBlock.Members
End Sub
Public Sub GetPartsOfObjectCreationExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef argumentList As SyntaxNode, ByRef initializer As SyntaxNode) Implements ISyntaxFacts.GetPartsOfObjectCreationExpression
Dim objectCreationExpression = DirectCast(node, ObjectCreationExpressionSyntax)
type = objectCreationExpression.Type
argumentList = objectCreationExpression.ArgumentList
initializer = objectCreationExpression.Initializer
End Sub
Public Sub GetPartsOfParenthesizedExpression(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression
Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax)
openParen = parenthesizedExpression.OpenParenToken
expression = parenthesizedExpression.Expression
closeParen = parenthesizedExpression.CloseParenToken
End Sub
Public Sub GetPartsOfPrefixUnaryExpression(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef operand As SyntaxNode) Implements ISyntaxFacts.GetPartsOfPrefixUnaryExpression
Dim unaryExpression = DirectCast(node, UnaryExpressionSyntax)
operatorToken = unaryExpression.OperatorToken
operand = unaryExpression.Operand
End Sub
Public Sub GetPartsOfQualifiedName(node As SyntaxNode, ByRef left As SyntaxNode, ByRef dotToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfQualifiedName
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
left = qualifiedName.Left
dotToken = qualifiedName.DotToken
right = qualifiedName.Right
End Sub
#End Region
#Region "GetXXXOfYYY members"
Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).Expression
End Function
Public Function GetExpressionOfThrowExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression
' ThrowExpression doesn't exist in VB
Throw New NotImplementedException()
End Function
#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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports System.Diagnostics.CodeAnalysis
#If CODE_STYLE Then
Imports Microsoft.CodeAnalysis.Internal.Editing
#Else
Imports Microsoft.CodeAnalysis.Editing
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Friend Class VisualBasicSyntaxFacts
Inherits AbstractSyntaxFacts
Implements ISyntaxFacts
Public Shared ReadOnly Property Instance As New VisualBasicSyntaxFacts
Protected Sub New()
End Sub
Public ReadOnly Property IsCaseSensitive As Boolean Implements ISyntaxFacts.IsCaseSensitive
Get
Return False
End Get
End Property
Public ReadOnly Property StringComparer As StringComparer Implements ISyntaxFacts.StringComparer
Get
Return CaseInsensitiveComparison.Comparer
End Get
End Property
Public ReadOnly Property ElasticMarker As SyntaxTrivia Implements ISyntaxFacts.ElasticMarker
Get
Return SyntaxFactory.ElasticMarker
End Get
End Property
Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFacts.ElasticCarriageReturnLineFeed
Get
Return SyntaxFactory.ElasticCarriageReturnLineFeed
End Get
End Property
Public Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds = VisualBasicSyntaxKinds.Instance Implements ISyntaxFacts.SyntaxKinds
Public Function SupportsIndexingInitializer(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsIndexingInitializer
Return False
End Function
Public Function SupportsThrowExpression(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsThrowExpression
Return False
End Function
Public Function SupportsLocalFunctionDeclaration(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsLocalFunctionDeclaration
Return False
End Function
Public Function SupportsRecord(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecord
Return False
End Function
Public Function SupportsRecordStruct(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsRecordStruct
Return False
End Function
Public Function ParseToken(text As String) As SyntaxToken Implements ISyntaxFacts.ParseToken
Return SyntaxFactory.ParseToken(text, startStatement:=True)
End Function
Public Function ParseLeadingTrivia(text As String) As SyntaxTriviaList Implements ISyntaxFacts.ParseLeadingTrivia
Return SyntaxFactory.ParseLeadingTrivia(text)
End Function
Public Function EscapeIdentifier(identifier As String) As String Implements ISyntaxFacts.EscapeIdentifier
Dim keywordKind = SyntaxFacts.GetKeywordKind(identifier)
Dim needsEscaping = keywordKind <> SyntaxKind.None
Return If(needsEscaping, "[" & identifier & "]", identifier)
End Function
Public Function IsVerbatimIdentifier(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return False
End Function
Public Function IsOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsOperator
Return (IsUnaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is UnaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax)) OrElse
(IsBinaryExpressionOperatorToken(CType(token.Kind, SyntaxKind)) AndAlso (TypeOf token.Parent Is BinaryExpressionSyntax OrElse TypeOf token.Parent Is OperatorStatementSyntax))
End Function
Public Function IsContextualKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsContextualKeyword
Return token.IsContextualKeyword()
End Function
Public Function IsReservedKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsReservedKeyword
Return token.IsReservedKeyword()
End Function
Public Function IsPreprocessorKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPreprocessorKeyword
Return token.IsPreprocessorKeyword()
End Function
Public Function IsPreProcessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsPreProcessorDirectiveContext
Return syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)
End Function
Public Function TryGetCorrespondingOpenBrace(token As SyntaxToken, ByRef openBrace As SyntaxToken) As Boolean Implements ISyntaxFacts.TryGetCorrespondingOpenBrace
If token.Kind = SyntaxKind.CloseBraceToken Then
Dim tuples = token.Parent.GetBraces()
openBrace = tuples.openBrace
Return openBrace.Kind = SyntaxKind.OpenBraceToken
End If
Return False
End Function
Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.IsEntirelyWithinStringOrCharOrNumericLiteral
If syntaxTree Is Nothing Then
Return False
End If
Return syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken)
End Function
Public Function IsDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDirective
Return TypeOf node Is DirectiveTriviaSyntax
End Function
Public Function TryGetExternalSourceInfo(node As SyntaxNode, ByRef info As ExternalSourceInfo) As Boolean Implements ISyntaxFacts.TryGetExternalSourceInfo
Select Case node.Kind
Case SyntaxKind.ExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(CInt(DirectCast(node, ExternalSourceDirectiveTriviaSyntax).LineStart.Value), False)
Return True
Case SyntaxKind.EndExternalSourceDirectiveTrivia
info = New ExternalSourceInfo(Nothing, True)
Return True
End Select
Return False
End Function
Public Function IsDeclarationExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationExpression
' VB doesn't support declaration expressions
Return False
End Function
Public Function IsAttributeName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeName
Return node.IsParentKind(SyntaxKind.Attribute) AndAlso
DirectCast(node.Parent, AttributeSyntax).Name Is node
End Function
Public Function IsNameOfSimpleMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSimpleMemberAccessExpression
Dim vbNode = TryCast(node, ExpressionSyntax)
Return vbNode IsNot Nothing AndAlso vbNode.IsSimpleMemberAccessExpressionName()
End Function
Public Function IsNameOfAnyMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfAnyMemberAccessExpression
Dim memberAccess = TryCast(node?.Parent, MemberAccessExpressionSyntax)
Return memberAccess IsNot Nothing AndAlso memberAccess.Name Is node
End Function
Public Function GetStandaloneExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetStandaloneExpression
Return SyntaxFactory.GetStandaloneExpression(TryCast(node, ExpressionSyntax))
End Function
Public Function GetRootConditionalAccessExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRootConditionalAccessExpression
Return TryCast(node, ExpressionSyntax).GetRootConditionalAccessExpression()
End Function
Public Function IsNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNamedArgument
Dim arg = TryCast(node, SimpleArgumentSyntax)
Return arg?.NameColonEquals IsNot Nothing
End Function
Public Function IsNameOfNamedArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfNamedArgument
Return node.CheckParent(Of SimpleArgumentSyntax)(Function(p) p.IsNamed AndAlso p.NameColonEquals.Name Is node)
End Function
Public Function GetNameOfParameter(node As SyntaxNode) As SyntaxToken? Implements ISyntaxFacts.GetNameOfParameter
Return DirectCast(node, ParameterSyntax).Identifier?.Identifier
End Function
Public Function GetDefaultOfParameter(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetDefaultOfParameter
Return DirectCast(node, ParameterSyntax).Default
End Function
Public Function GetParameterList(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetParameterList
Return node.GetParameterList()
End Function
Public Function IsParameterList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterList
Return node.IsKind(SyntaxKind.ParameterList)
End Function
Public Function ISyntaxFacts_HasIncompleteParentMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.HasIncompleteParentMember
Return HasIncompleteParentMember(node)
End Function
Public Function GetIdentifierOfGenericName(genericName As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfGenericName
Return DirectCast(genericName, GenericNameSyntax).Identifier
End Function
Public Function IsUsingDirectiveName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingDirectiveName
Return node.IsParentKind(SyntaxKind.SimpleImportsClause) AndAlso
DirectCast(node.Parent, SimpleImportsClauseSyntax).Name Is node
End Function
Public Function IsDeconstructionAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionAssignment
Return False
End Function
Public Function IsDeconstructionForEachStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeconstructionForEachStatement
Return False
End Function
Public Function IsStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatement
Return TypeOf node Is StatementSyntax
End Function
Public Function IsExecutableStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableStatement
Return TypeOf node Is ExecutableStatementSyntax
End Function
Public Function IsMethodBody(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodBody
Return TypeOf node Is MethodBlockBaseSyntax
End Function
Public Function GetExpressionOfReturnStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfReturnStatement
Return DirectCast(node, ReturnStatementSyntax).Expression
End Function
Public Function IsThisConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsThisConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsThisConstructorInitializer()
End If
Return False
End Function
Public Function IsBaseConstructorInitializer(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsBaseConstructorInitializer
If TypeOf token.Parent Is IdentifierNameSyntax AndAlso token.HasMatchingText(SyntaxKind.NewKeyword) Then
Dim memberAccess = TryCast(token.Parent.Parent, MemberAccessExpressionSyntax)
Return memberAccess.IsBaseConstructorInitializer()
End If
Return False
End Function
Public Function IsQueryKeyword(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsQueryKeyword
Select Case token.Kind()
Case _
SyntaxKind.JoinKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.AggregateKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.WhereKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.SelectKeyword
Return TypeOf token.Parent Is QueryClauseSyntax
Case SyntaxKind.GroupKeyword
Return (TypeOf token.Parent Is QueryClauseSyntax) OrElse (token.Parent.IsKind(SyntaxKind.GroupAggregation))
Case SyntaxKind.EqualsKeyword
Return TypeOf token.Parent Is JoinConditionSyntax
Case SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword
Return TypeOf token.Parent Is OrderingSyntax
Case SyntaxKind.InKeyword
Return TypeOf token.Parent Is CollectionRangeVariableSyntax
Case Else
Return False
End Select
End Function
Public Function IsPredefinedType(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType <> PredefinedType.None
End Function
Public Function IsPredefinedType(token As SyntaxToken, type As PredefinedType) As Boolean Implements ISyntaxFacts.IsPredefinedType
Dim actualType As PredefinedType = PredefinedType.None
Return TryGetPredefinedType(token, actualType) AndAlso actualType = type
End Function
Public Function TryGetPredefinedType(token As SyntaxToken, ByRef type As PredefinedType) As Boolean Implements ISyntaxFacts.TryGetPredefinedType
type = GetPredefinedType(token)
Return type <> PredefinedType.None
End Function
Private Shared Function GetPredefinedType(token As SyntaxToken) As PredefinedType
Select Case token.Kind
Case SyntaxKind.BooleanKeyword
Return PredefinedType.Boolean
Case SyntaxKind.ByteKeyword
Return PredefinedType.Byte
Case SyntaxKind.SByteKeyword
Return PredefinedType.SByte
Case SyntaxKind.IntegerKeyword
Return PredefinedType.Int32
Case SyntaxKind.UIntegerKeyword
Return PredefinedType.UInt32
Case SyntaxKind.ShortKeyword
Return PredefinedType.Int16
Case SyntaxKind.UShortKeyword
Return PredefinedType.UInt16
Case SyntaxKind.LongKeyword
Return PredefinedType.Int64
Case SyntaxKind.ULongKeyword
Return PredefinedType.UInt64
Case SyntaxKind.SingleKeyword
Return PredefinedType.Single
Case SyntaxKind.DoubleKeyword
Return PredefinedType.Double
Case SyntaxKind.DecimalKeyword
Return PredefinedType.Decimal
Case SyntaxKind.StringKeyword
Return PredefinedType.String
Case SyntaxKind.CharKeyword
Return PredefinedType.Char
Case SyntaxKind.ObjectKeyword
Return PredefinedType.Object
Case SyntaxKind.DateKeyword
Return PredefinedType.DateTime
Case Else
Return PredefinedType.None
End Select
End Function
Public Function IsPredefinedOperator(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp <> PredefinedOperator.None
End Function
Public Function IsPredefinedOperator(token As SyntaxToken, op As PredefinedOperator) As Boolean Implements ISyntaxFacts.IsPredefinedOperator
Dim actualOp As PredefinedOperator = PredefinedOperator.None
Return TryGetPredefinedOperator(token, actualOp) AndAlso actualOp = op
End Function
Public Function TryGetPredefinedOperator(token As SyntaxToken, ByRef op As PredefinedOperator) As Boolean Implements ISyntaxFacts.TryGetPredefinedOperator
op = GetPredefinedOperator(token)
Return op <> PredefinedOperator.None
End Function
Private Shared Function GetPredefinedOperator(token As SyntaxToken) As PredefinedOperator
Select Case token.Kind
Case SyntaxKind.PlusToken, SyntaxKind.PlusEqualsToken
Return PredefinedOperator.Addition
Case SyntaxKind.MinusToken, SyntaxKind.MinusEqualsToken
Return PredefinedOperator.Subtraction
Case SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword
Return PredefinedOperator.BitwiseAnd
Case SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword
Return PredefinedOperator.BitwiseOr
Case SyntaxKind.AmpersandToken, SyntaxKind.AmpersandEqualsToken
Return PredefinedOperator.Concatenate
Case SyntaxKind.SlashToken, SyntaxKind.SlashEqualsToken
Return PredefinedOperator.Division
Case SyntaxKind.EqualsToken
Return PredefinedOperator.Equality
Case SyntaxKind.XorKeyword
Return PredefinedOperator.ExclusiveOr
Case SyntaxKind.CaretToken, SyntaxKind.CaretEqualsToken
Return PredefinedOperator.Exponent
Case SyntaxKind.GreaterThanToken
Return PredefinedOperator.GreaterThan
Case SyntaxKind.GreaterThanEqualsToken
Return PredefinedOperator.GreaterThanOrEqual
Case SyntaxKind.LessThanGreaterThanToken
Return PredefinedOperator.Inequality
Case SyntaxKind.BackslashToken, SyntaxKind.BackslashEqualsToken
Return PredefinedOperator.IntegerDivision
Case SyntaxKind.LessThanLessThanToken, SyntaxKind.LessThanLessThanEqualsToken
Return PredefinedOperator.LeftShift
Case SyntaxKind.LessThanToken
Return PredefinedOperator.LessThan
Case SyntaxKind.LessThanEqualsToken
Return PredefinedOperator.LessThanOrEqual
Case SyntaxKind.LikeKeyword
Return PredefinedOperator.Like
Case SyntaxKind.NotKeyword
Return PredefinedOperator.Complement
Case SyntaxKind.ModKeyword
Return PredefinedOperator.Modulus
Case SyntaxKind.AsteriskToken, SyntaxKind.AsteriskEqualsToken
Return PredefinedOperator.Multiplication
Case SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.GreaterThanGreaterThanEqualsToken
Return PredefinedOperator.RightShift
Case Else
Return PredefinedOperator.None
End Select
End Function
Public Function GetText(kind As Integer) As String Implements ISyntaxFacts.GetText
Return SyntaxFacts.GetText(CType(kind, SyntaxKind))
End Function
Public Function IsIdentifierPartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierPartCharacter
Return SyntaxFacts.IsIdentifierPartCharacter(c)
End Function
Public Function IsIdentifierStartCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierStartCharacter
Return SyntaxFacts.IsIdentifierStartCharacter(c)
End Function
Public Function IsIdentifierEscapeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsIdentifierEscapeCharacter
Return c = "["c OrElse c = "]"c
End Function
Public Function IsValidIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsValidIdentifier
Dim token = SyntaxFactory.ParseToken(identifier)
' TODO: There is no way to get the diagnostics to see if any are actually errors?
Return IsIdentifier(token) AndAlso Not token.ContainsDiagnostics AndAlso token.ToString().Length = identifier.Length
End Function
Public Function IsVerbatimIdentifier(identifier As String) As Boolean Implements ISyntaxFacts.IsVerbatimIdentifier
Return IsValidIdentifier(identifier) AndAlso MakeHalfWidthIdentifier(identifier.First()) = "[" AndAlso MakeHalfWidthIdentifier(identifier.Last()) = "]"
End Function
Public Function IsTypeCharacter(c As Char) As Boolean Implements ISyntaxFacts.IsTypeCharacter
Return c = "%"c OrElse
c = "&"c OrElse
c = "@"c OrElse
c = "!"c OrElse
c = "#"c OrElse
c = "$"c
End Function
Public Function IsStartOfUnicodeEscapeSequence(c As Char) As Boolean Implements ISyntaxFacts.IsStartOfUnicodeEscapeSequence
Return False ' VB does not support identifiers with escaped unicode characters
End Function
Public Function IsLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsLiteral
Select Case token.Kind()
Case _
SyntaxKind.IntegerLiteralToken,
SyntaxKind.CharacterLiteralToken,
SyntaxKind.DecimalLiteralToken,
SyntaxKind.FloatingLiteralToken,
SyntaxKind.DateLiteralToken,
SyntaxKind.StringLiteralToken,
SyntaxKind.DollarSignDoubleQuoteToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.InterpolatedStringTextToken,
SyntaxKind.TrueKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.NothingKeyword
Return True
End Select
Return False
End Function
Public Function IsStringLiteralOrInterpolatedStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsStringLiteralOrInterpolatedStringLiteral
Return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken)
End Function
Public Function IsBindableToken(token As Microsoft.CodeAnalysis.SyntaxToken) As Boolean Implements ISyntaxFacts.IsBindableToken
Return Me.IsWord(token) OrElse
Me.IsLiteral(token) OrElse
Me.IsOperator(token)
End Function
Public Function IsPointerMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPointerMemberAccessExpression
Return False
End Function
Public Sub GetNameAndArityOfSimpleName(node As SyntaxNode, ByRef name As String, ByRef arity As Integer) Implements ISyntaxFacts.GetNameAndArityOfSimpleName
Dim simpleName = DirectCast(node, SimpleNameSyntax)
name = simpleName.Identifier.ValueText
arity = simpleName.Arity
End Sub
Public Function LooksGeneric(name As SyntaxNode) As Boolean Implements ISyntaxFacts.LooksGeneric
Return name.IsKind(SyntaxKind.GenericName)
End Function
Public Function GetExpressionOfMemberAccessExpression(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfMemberAccessExpression
Return TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget)
End Function
Public Function GetTargetOfMemberBinding(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTargetOfMemberBinding
' Member bindings are a C# concept.
Return Nothing
End Function
Public Function GetNameOfMemberBindingExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetNameOfMemberBindingExpression
' Member bindings are a C# concept.
Return Nothing
End Function
Public Sub GetPartsOfElementAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfElementAccessExpression
Dim invocation = TryCast(node, InvocationExpressionSyntax)
If invocation IsNot Nothing Then
expression = invocation?.Expression
argumentList = invocation?.ArgumentList
Return
End If
If node.Kind() = SyntaxKind.DictionaryAccessExpression Then
GetPartsOfMemberAccessExpression(node, expression, argumentList)
Return
End If
Throw ExceptionUtilities.UnexpectedValue(node.Kind())
End Sub
Public Function GetExpressionOfInterpolation(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfInterpolation
Return DirectCast(node, InterpolationSyntax).Expression
End Function
Public Function IsInNamespaceOrTypeContext(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInNamespaceOrTypeContext
Return SyntaxFacts.IsInNamespaceOrTypeContext(node)
End Function
Public Function IsBaseTypeList(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseTypeList
Return TryCast(node, InheritsOrImplementsStatementSyntax) IsNot Nothing
End Function
Public Function IsInStaticContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInStaticContext
Return node.IsInStaticContext()
End Function
Public Function GetExpressionOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetExpressionOfArgument
Return DirectCast(node, ArgumentSyntax).GetArgumentExpression()
End Function
Public Function GetRefKindOfArgument(node As Microsoft.CodeAnalysis.SyntaxNode) As Microsoft.CodeAnalysis.RefKind Implements ISyntaxFacts.GetRefKindOfArgument
' TODO(cyrusn): Consider the method this argument is passed to, to determine this.
Return RefKind.None
End Function
Public Function IsArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsArgument
Return TypeOf node Is ArgumentSyntax
End Function
Public Function IsSimpleArgument(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleArgument
Dim argument = TryCast(node, ArgumentSyntax)
Return argument IsNot Nothing AndAlso Not argument.IsNamed AndAlso Not argument.IsOmitted
End Function
Public Function IsInConstantContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstantContext
Return node.IsInConstantContext()
End Function
Public Function IsInConstructor(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsInConstructor
Return node.GetAncestors(Of StatementSyntax).Any(Function(s) s.Kind = SyntaxKind.ConstructorBlock)
End Function
Public Function IsUnsafeContext(node As Microsoft.CodeAnalysis.SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnsafeContext
Return False
End Function
Public Function GetNameOfAttribute(node As SyntaxNode) As Microsoft.CodeAnalysis.SyntaxNode Implements ISyntaxFacts.GetNameOfAttribute
Return DirectCast(node, AttributeSyntax).Name
End Function
Public Function IsAttributeNamedArgumentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAttributeNamedArgumentIdentifier
Dim identifierName = TryCast(node, IdentifierNameSyntax)
Return identifierName.IsParentKind(SyntaxKind.NameColonEquals) AndAlso
identifierName.Parent.IsParentKind(SyntaxKind.SimpleArgument) AndAlso
identifierName.Parent.Parent.IsParentKind(SyntaxKind.ArgumentList) AndAlso
identifierName.Parent.Parent.Parent.IsParentKind(SyntaxKind.Attribute)
End Function
Public Function GetContainingTypeDeclaration(root As SyntaxNode, position As Integer) As SyntaxNode Implements ISyntaxFacts.GetContainingTypeDeclaration
If root Is Nothing Then
Throw New ArgumentNullException(NameOf(root))
End If
If position < 0 OrElse position > root.Span.End Then
Throw New ArgumentOutOfRangeException(NameOf(position))
End If
Return root.
FindToken(position).
GetAncestors(Of SyntaxNode)().
FirstOrDefault(Function(n) TypeOf n Is TypeBlockSyntax OrElse TypeOf n Is DelegateStatementSyntax)
End Function
Public Function GetContainingVariableDeclaratorOfFieldDeclaration(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetContainingVariableDeclaratorOfFieldDeclaration
If node Is Nothing Then
Throw New ArgumentNullException(NameOf(node))
End If
Dim parent = node.Parent
While node IsNot Nothing
If node.Kind = SyntaxKind.VariableDeclarator AndAlso node.IsParentKind(SyntaxKind.FieldDeclaration) Then
Return node
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim unused As SyntaxNode = Nothing
Return IsMemberInitializerNamedAssignmentIdentifier(node, unused)
End Function
Public Function IsMemberInitializerNamedAssignmentIdentifier(
node As SyntaxNode,
ByRef initializedInstance As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberInitializerNamedAssignmentIdentifier
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier?.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
' .parent is the NamedField.
' .parent.parent is the ObjectInitializer.
' .parent.parent.parent will be the ObjectCreationExpression.
initializedInstance = identifier.Parent.Parent.Parent
Return True
End If
Return False
End Function
Public Function IsNameOfSubpattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfSubpattern
Return False
End Function
Public Function IsPropertyPatternClause(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPropertyPatternClause
Return False
End Function
Public Function IsElementAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsElementAccessExpression
' VB doesn't have a specialized node for element access. Instead, it just uses an
' invocation expression or dictionary access expression.
Return node.Kind = SyntaxKind.InvocationExpression OrElse node.Kind = SyntaxKind.DictionaryAccessExpression
End Function
Public Function IsIndexerMemberCRef(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIndexerMemberCRef
Return False
End Function
Public Function GetContainingMemberDeclaration(root As SyntaxNode, position As Integer, Optional useFullSpan As Boolean = True) As SyntaxNode Implements ISyntaxFacts.GetContainingMemberDeclaration
Contract.ThrowIfNull(root, NameOf(root))
Contract.ThrowIfTrue(position < 0 OrElse position > root.FullSpan.End, NameOf(position))
Dim [end] = root.FullSpan.End
If [end] = 0 Then
' empty file
Return Nothing
End If
' make sure position doesn't touch end of root
position = Math.Min(position, [end] - 1)
Dim node = root.FindToken(position).Parent
While node IsNot Nothing
If useFullSpan OrElse node.Span.Contains(position) Then
If TypeOf node Is MethodBlockBaseSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is MethodBaseSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return node
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return node
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return node
End If
If TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax OrElse
TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is FieldDeclarationSyntax Then
Return node
End If
End If
node = node.Parent
End While
Return Nothing
End Function
Public Function IsMethodLevelMember(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMethodLevelMember
' Note: Derived types of MethodBaseSyntax are expanded explicitly, since PropertyStatementSyntax and
' EventStatementSyntax will NOT be parented by MethodBlockBaseSyntax. Additionally, there are things
' like AccessorStatementSyntax and DelegateStatementSyntax that we never want to tread as method level
' members.
If TypeOf node Is MethodStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is SubNewStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is OperatorStatementSyntax AndAlso Not TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return True
End If
If TypeOf node Is PropertyStatementSyntax AndAlso Not TypeOf node.Parent Is PropertyBlockSyntax Then
Return True
End If
If TypeOf node Is EventStatementSyntax AndAlso Not TypeOf node.Parent Is EventBlockSyntax Then
Return True
End If
If TypeOf node Is DeclareStatementSyntax Then
Return True
End If
Return TypeOf node Is ConstructorBlockSyntax OrElse
TypeOf node Is MethodBlockSyntax OrElse
TypeOf node Is OperatorBlockSyntax OrElse
TypeOf node Is EventBlockSyntax OrElse
TypeOf node Is PropertyBlockSyntax OrElse
TypeOf node Is EnumMemberDeclarationSyntax OrElse
TypeOf node Is FieldDeclarationSyntax
End Function
Public Function GetMemberBodySpanForSpeculativeBinding(node As SyntaxNode) As TextSpan Implements ISyntaxFacts.GetMemberBodySpanForSpeculativeBinding
Dim member = GetContainingMemberDeclaration(node, node.SpanStart)
If member Is Nothing Then
Return Nothing
End If
' TODO: currently we only support method for now
Dim method = TryCast(member, MethodBlockBaseSyntax)
If method IsNot Nothing Then
If method.BlockStatement Is Nothing OrElse method.EndBlockStatement Is Nothing Then
Return Nothing
End If
' We don't want to include the BlockStatement or any trailing trivia up to and including its statement
' terminator in the span. Instead, we use the start of the first statement's leading trivia (if any) up
' to the start of the EndBlockStatement. If there aren't any statements in the block, we use the start
' of the EndBlockStatements leading trivia.
Dim firstStatement = method.Statements.FirstOrDefault()
Dim spanStart = If(firstStatement IsNot Nothing,
firstStatement.FullSpan.Start,
method.EndBlockStatement.FullSpan.Start)
Return TextSpan.FromBounds(spanStart, method.EndBlockStatement.SpanStart)
End If
Return Nothing
End Function
Public Function ContainsInMemberBody(node As SyntaxNode, span As TextSpan) As Boolean Implements ISyntaxFacts.ContainsInMemberBody
Dim method = TryCast(node, MethodBlockBaseSyntax)
If method IsNot Nothing Then
Return method.Statements.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan(method.Statements), span)
End If
Dim [event] = TryCast(node, EventBlockSyntax)
If [event] IsNot Nothing Then
Return [event].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([event].Accessors), span)
End If
Dim [property] = TryCast(node, PropertyBlockSyntax)
If [property] IsNot Nothing Then
Return [property].Accessors.Count > 0 AndAlso ContainsExclusively(GetSyntaxListSpan([property].Accessors), span)
End If
Dim field = TryCast(node, FieldDeclarationSyntax)
If field IsNot Nothing Then
Return field.Declarators.Count > 0 AndAlso ContainsExclusively(GetSeparatedSyntaxListSpan(field.Declarators), span)
End If
Dim [enum] = TryCast(node, EnumMemberDeclarationSyntax)
If [enum] IsNot Nothing Then
Return [enum].Initializer IsNot Nothing AndAlso ContainsExclusively([enum].Initializer.Span, span)
End If
Dim propStatement = TryCast(node, PropertyStatementSyntax)
If propStatement IsNot Nothing Then
Return propStatement.Initializer IsNot Nothing AndAlso ContainsExclusively(propStatement.Initializer.Span, span)
End If
Return False
End Function
Private Shared Function ContainsExclusively(outerSpan As TextSpan, innerSpan As TextSpan) As Boolean
If innerSpan.IsEmpty Then
Return outerSpan.Contains(innerSpan.Start)
End If
Return outerSpan.Contains(innerSpan)
End Function
Private Shared Function GetSyntaxListSpan(Of T As SyntaxNode)(list As SyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Shared Function GetSeparatedSyntaxListSpan(Of T As SyntaxNode)(list As SeparatedSyntaxList(Of T)) As TextSpan
Debug.Assert(list.Count > 0)
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Public Function GetTopLevelAndMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetTopLevelAndMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=True, methodLevel:=True)
Return list
End Function
Public Function GetMethodLevelMembers(root As SyntaxNode) As List(Of SyntaxNode) Implements ISyntaxFacts.GetMethodLevelMembers
Dim list = New List(Of SyntaxNode)()
AppendMembers(root, list, topLevel:=False, methodLevel:=True)
Return list
End Function
Public Function GetMembersOfTypeDeclaration(typeDeclaration As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetMembersOfTypeDeclaration
Return DirectCast(typeDeclaration, TypeBlockSyntax).Members
End Function
Public Function IsTopLevelNodeWithMembers(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTopLevelNodeWithMembers
Return TypeOf node Is NamespaceBlockSyntax OrElse
TypeOf node Is TypeBlockSyntax OrElse
TypeOf node Is EnumBlockSyntax
End Function
Private Const s_dotToken As String = "."
Public Function GetDisplayName(node As SyntaxNode, options As DisplayNameOptions, Optional rootNamespace As String = Nothing) As String Implements ISyntaxFacts.GetDisplayName
If node Is Nothing Then
Return String.Empty
End If
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
' member keyword (if any)
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If (options And DisplayNameOptions.IncludeMemberKeyword) <> 0 Then
Dim keywordToken = memberDeclaration.GetMemberKeywordToken()
If keywordToken <> Nothing AndAlso Not keywordToken.IsMissing Then
builder.Append(keywordToken.Text)
builder.Append(" "c)
End If
End If
Dim names = ArrayBuilder(Of String).GetInstance()
' containing type(s)
Dim parent = node.Parent
While TypeOf parent Is TypeBlockSyntax
names.Push(GetName(parent, options, containsGlobalKeyword:=False))
parent = parent.Parent
End While
If (options And DisplayNameOptions.IncludeNamespaces) <> 0 Then
' containing namespace(s) in source (if any)
Dim containsGlobalKeyword As Boolean = False
While parent IsNot Nothing AndAlso parent.Kind() = SyntaxKind.NamespaceBlock
names.Push(GetName(parent, options, containsGlobalKeyword))
parent = parent.Parent
End While
' root namespace (if any)
If Not containsGlobalKeyword AndAlso Not String.IsNullOrEmpty(rootNamespace) Then
builder.Append(rootNamespace)
builder.Append(s_dotToken)
End If
End If
While Not names.IsEmpty()
Dim name = names.Pop()
If name IsNot Nothing Then
builder.Append(name)
builder.Append(s_dotToken)
End If
End While
names.Free()
' name (include generic type parameters)
builder.Append(GetName(node, options, containsGlobalKeyword:=False))
' parameter list (if any)
If (options And DisplayNameOptions.IncludeParameters) <> 0 Then
builder.Append(memberDeclaration.GetParameterList())
End If
' As clause (if any)
If (options And DisplayNameOptions.IncludeType) <> 0 Then
Dim asClause = memberDeclaration.GetAsClause()
If asClause IsNot Nothing Then
builder.Append(" "c)
builder.Append(asClause)
End If
End If
Return pooled.ToStringAndFree()
End Function
Private Shared Function GetName(node As SyntaxNode, options As DisplayNameOptions, ByRef containsGlobalKeyword As Boolean) As String
Const missingTokenPlaceholder As String = "?"
Select Case node.Kind()
Case SyntaxKind.CompilationUnit
Return Nothing
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(node, IdentifierNameSyntax).Identifier
Return If(identifier.IsMissing, missingTokenPlaceholder, identifier.Text)
Case SyntaxKind.IncompleteMember
Return missingTokenPlaceholder
Case SyntaxKind.NamespaceBlock
Dim nameSyntax = CType(node, NamespaceBlockSyntax).NamespaceStatement.Name
If nameSyntax.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return Nothing
Else
Return GetName(nameSyntax, options, containsGlobalKeyword)
End If
Case SyntaxKind.QualifiedName
Dim qualified = CType(node, QualifiedNameSyntax)
If qualified.Left.Kind() = SyntaxKind.GlobalName Then
containsGlobalKeyword = True
Return GetName(qualified.Right, options, containsGlobalKeyword) ' don't use the Global prefix if specified
Else
Return GetName(qualified.Left, options, containsGlobalKeyword) + s_dotToken + GetName(qualified.Right, options, containsGlobalKeyword)
End If
End Select
Dim name As String = Nothing
Dim memberDeclaration = TryCast(node, DeclarationStatementSyntax)
If memberDeclaration IsNot Nothing Then
Dim nameToken = memberDeclaration.GetNameToken()
If nameToken <> Nothing Then
name = If(nameToken.IsMissing, missingTokenPlaceholder, nameToken.Text)
If (options And DisplayNameOptions.IncludeTypeParameters) <> 0 Then
Dim pooled = PooledStringBuilder.GetInstance()
Dim builder = pooled.Builder
builder.Append(name)
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList())
name = pooled.ToStringAndFree()
End If
End If
End If
Debug.Assert(name IsNot Nothing, "Unexpected node type " + node.Kind().ToString())
Return name
End Function
Private Shared Sub AppendTypeParameterList(builder As StringBuilder, typeParameterList As TypeParameterListSyntax)
If typeParameterList IsNot Nothing AndAlso typeParameterList.Parameters.Count > 0 Then
builder.Append("(Of ")
builder.Append(typeParameterList.Parameters(0).Identifier.Text)
For i = 1 To typeParameterList.Parameters.Count - 1
builder.Append(", ")
builder.Append(typeParameterList.Parameters(i).Identifier.Text)
Next
builder.Append(")"c)
End If
End Sub
Private Sub AppendMembers(node As SyntaxNode, list As List(Of SyntaxNode), topLevel As Boolean, methodLevel As Boolean)
Debug.Assert(topLevel OrElse methodLevel)
For Each member In node.GetMembers()
If IsTopLevelNodeWithMembers(member) Then
If topLevel Then
list.Add(member)
End If
AppendMembers(member, list, topLevel, methodLevel)
Continue For
End If
If methodLevel AndAlso IsMethodLevelMember(member) Then
list.Add(member)
End If
Next
End Sub
Public Function TryGetBindableParent(token As SyntaxToken) As SyntaxNode Implements ISyntaxFacts.TryGetBindableParent
Dim node = token.Parent
While node IsNot Nothing
Dim parent = node.Parent
' If this node is on the left side of a member access expression, don't ascend
' further or we'll end up binding to something else.
Dim memberAccess = TryCast(parent, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing Then
If memberAccess.Expression Is node Then
Exit While
End If
End If
' If this node is on the left side of a qualified name, don't ascend
' further or we'll end up binding to something else.
Dim qualifiedName = TryCast(parent, QualifiedNameSyntax)
If qualifiedName IsNot Nothing Then
If qualifiedName.Left Is node Then
Exit While
End If
End If
' If this node is the type of an object creation expression, return the
' object creation expression.
Dim objectCreation = TryCast(parent, ObjectCreationExpressionSyntax)
If objectCreation IsNot Nothing Then
If objectCreation.Type Is node Then
node = parent
Exit While
End If
End If
' The inside of an interpolated string is treated as its own token so we
' need to force navigation to the parent expression syntax.
If TypeOf node Is InterpolatedStringTextSyntax AndAlso TypeOf parent Is InterpolatedStringExpressionSyntax Then
node = parent
Exit While
End If
' If this node is not parented by a name, we're done.
Dim name = TryCast(parent, NameSyntax)
If name Is Nothing Then
Exit While
End If
node = parent
End While
Return node
End Function
Public Function GetConstructors(root As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Implements ISyntaxFacts.GetConstructors
Dim compilationUnit = TryCast(root, CompilationUnitSyntax)
If compilationUnit Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim constructors = New List(Of SyntaxNode)()
AppendConstructors(compilationUnit.Members, constructors, cancellationToken)
Return constructors
End Function
Private Sub AppendConstructors(members As SyntaxList(Of StatementSyntax), constructors As List(Of SyntaxNode), cancellationToken As CancellationToken)
For Each member As StatementSyntax In members
cancellationToken.ThrowIfCancellationRequested()
Dim constructor = TryCast(member, ConstructorBlockSyntax)
If constructor IsNot Nothing Then
constructors.Add(constructor)
Continue For
End If
Dim [namespace] = TryCast(member, NamespaceBlockSyntax)
If [namespace] IsNot Nothing Then
AppendConstructors([namespace].Members, constructors, cancellationToken)
End If
Dim [class] = TryCast(member, ClassBlockSyntax)
If [class] IsNot Nothing Then
AppendConstructors([class].Members, constructors, cancellationToken)
End If
Dim [struct] = TryCast(member, StructureBlockSyntax)
If [struct] IsNot Nothing Then
AppendConstructors([struct].Members, constructors, cancellationToken)
End If
Next
End Sub
Public Function GetInactiveRegionSpanAroundPosition(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As TextSpan Implements ISyntaxFacts.GetInactiveRegionSpanAroundPosition
Dim trivia = tree.FindTriviaToLeft(position, cancellationToken)
If trivia.Kind = SyntaxKind.DisabledTextTrivia Then
Return trivia.FullSpan
End If
Return Nothing
End Function
Public Function GetNameForArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForArgument
If TryCast(argument, ArgumentSyntax)?.IsNamed Then
Return DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Identifier.ValueText
End If
Return String.Empty
End Function
Public Function GetNameForAttributeArgument(argument As SyntaxNode) As String Implements ISyntaxFacts.GetNameForAttributeArgument
' All argument types are ArgumentSyntax in VB.
Return GetNameForArgument(argument)
End Function
Public Function IsLeftSideOfDot(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfDot
Return TryCast(node, ExpressionSyntax).IsLeftSideOfDot()
End Function
Public Function GetRightSideOfDot(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Right,
TryCast(node, MemberAccessExpressionSyntax)?.Name)
End Function
Public Function GetLeftSideOfDot(node As SyntaxNode, Optional allowImplicitTarget As Boolean = False) As SyntaxNode Implements ISyntaxFacts.GetLeftSideOfDot
Return If(TryCast(node, QualifiedNameSyntax)?.Left,
TryCast(node, MemberAccessExpressionSyntax)?.GetExpressionOfMemberAccessExpression(allowImplicitTarget))
End Function
Public Function IsLeftSideOfExplicitInterfaceSpecifier(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfExplicitInterfaceSpecifier
Return IsLeftSideOfDot(node) AndAlso TryCast(node.Parent.Parent, ImplementsClauseSyntax) IsNot Nothing
End Function
Public Function IsLeftSideOfAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfSimpleAssignmentStatement
End Function
Public Function IsLeftSideOfAnyAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfAnyAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfAnyAssignmentStatement
End Function
Public Function IsLeftSideOfCompoundAssignment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLeftSideOfCompoundAssignment
Return TryCast(node, ExpressionSyntax).IsLeftSideOfCompoundAssignmentStatement
End Function
Public Function GetRightHandSideOfAssignment(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetRightHandSideOfAssignment
Return DirectCast(node, AssignmentStatementSyntax).Right
End Function
Public Function IsInferredAnonymousObjectMemberDeclarator(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsInferredAnonymousObjectMemberDeclarator
Return node.IsKind(SyntaxKind.InferredFieldInitializer)
End Function
Public Function IsOperandOfIncrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementExpression
Return False
End Function
Public Function IsOperandOfIncrementOrDecrementExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOperandOfIncrementOrDecrementExpression
Return False
End Function
Public Function GetContentsOfInterpolatedString(interpolatedString As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentsOfInterpolatedString
Return (TryCast(interpolatedString, InterpolatedStringExpressionSyntax)?.Contents).Value
End Function
Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsNumericLiteral
Return token.Kind = SyntaxKind.DecimalLiteralToken OrElse
token.Kind = SyntaxKind.FloatingLiteralToken OrElse
token.Kind = SyntaxKind.IntegerLiteralToken
End Function
Public Function IsVerbatimStringLiteral(token As SyntaxToken) As Boolean Implements ISyntaxFacts.IsVerbatimStringLiteral
' VB does not have verbatim strings
Return False
End Function
Public Function GetArgumentsOfInvocationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfInvocationExpression
Dim argumentList = DirectCast(node, InvocationExpressionSyntax).ArgumentList
Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList))
End Function
Public Function GetArgumentsOfObjectCreationExpression(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfObjectCreationExpression
Dim argumentList = DirectCast(node, ObjectCreationExpressionSyntax).ArgumentList
Return If(argumentList Is Nothing, Nothing, GetArgumentsOfArgumentList(argumentList))
End Function
Public Function GetArgumentsOfArgumentList(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetArgumentsOfArgumentList
Return DirectCast(node, ArgumentListSyntax).Arguments
End Function
Public Function ConvertToSingleLine(node As SyntaxNode, Optional useElasticTrivia As Boolean = False) As SyntaxNode Implements ISyntaxFacts.ConvertToSingleLine
Return node.ConvertToSingleLine(useElasticTrivia)
End Function
Public Function IsDocumentationComment(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return node.IsKind(SyntaxKind.DocumentationCommentTrivia)
End Function
Public Function IsUsingOrExternOrImport(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingOrExternOrImport
Return node.IsKind(SyntaxKind.ImportsStatement)
End Function
Public Function IsGlobalAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalAssemblyAttribute
Return IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword)
End Function
Public Function IsModuleAssemblyAttribute(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsGlobalModuleAttribute
Return IsGlobalAttribute(node, SyntaxKind.ModuleKeyword)
End Function
Private Shared Function IsGlobalAttribute(node As SyntaxNode, attributeTarget As SyntaxKind) As Boolean
If node.IsKind(SyntaxKind.Attribute) Then
Dim attributeNode = CType(node, AttributeSyntax)
If attributeNode.Target IsNot Nothing Then
Return attributeNode.Target.AttributeModifier.IsKind(attributeTarget)
End If
End If
Return False
End Function
Public Function IsDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaration
' From the Visual Basic language spec:
' NamespaceMemberDeclaration :=
' NamespaceDeclaration |
' TypeDeclaration
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
' ClassMemberDeclaration ::=
' NonModuleDeclaration |
' EventMemberDeclaration |
' VariableMemberDeclaration |
' ConstantMemberDeclaration |
' MethodMemberDeclaration |
' PropertyMemberDeclaration |
' ConstructorMemberDeclaration |
' OperatorDeclaration
Select Case node.Kind()
' Because fields declarations can define multiple symbols "Public a, b As Integer"
' We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name.
Case SyntaxKind.VariableDeclarator
If (node.Parent.IsKind(SyntaxKind.FieldDeclaration)) Then
Return True
End If
Return False
Case SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumStatement,
SyntaxKind.EnumBlock,
SyntaxKind.StructureStatement,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceStatement,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassStatement,
SyntaxKind.ClassBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.EventStatement,
SyntaxKind.EventBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.FieldDeclaration,
SyntaxKind.SubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionStatement,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyStatement,
SyntaxKind.PropertyBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.SubNewStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorStatement,
SyntaxKind.OperatorBlock
Return True
End Select
Return False
End Function
' TypeDeclaration ::=
' ModuleDeclaration |
' NonModuleDeclaration
' NonModuleDeclaration ::=
' EnumDeclaration |
' StructureDeclaration |
' InterfaceDeclaration |
' ClassDeclaration |
' DelegateDeclaration
Public Function IsTypeDeclaration(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return True
End Select
Return False
End Function
Public Function IsSimpleAssignmentStatement(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleAssignmentStatement
Return node.IsKind(SyntaxKind.SimpleAssignmentStatement)
End Function
Public Sub GetPartsOfAssignmentStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentStatement
' VB only has assignment statements, so this can just delegate to that helper
GetPartsOfAssignmentExpressionOrStatement(statement, left, operatorToken, right)
End Sub
Public Sub GetPartsOfAssignmentExpressionOrStatement(statement As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfAssignmentExpressionOrStatement
Dim assignment = DirectCast(statement, AssignmentStatementSyntax)
left = assignment.Left
operatorToken = assignment.OperatorToken
right = assignment.Right
End Sub
Public Function GetIdentifierOfSimpleName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfSimpleName
Return DirectCast(node, SimpleNameSyntax).Identifier
End Function
Public Function GetIdentifierOfVariableDeclarator(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Last().Identifier
End Function
Public Function GetIdentifierOfParameter(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfParameter
Return DirectCast(node, ParameterSyntax).Identifier.Identifier
End Function
Public Function GetIdentifierOfTypeDeclaration(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfTypeDeclaration
Select Case node.Kind()
Case SyntaxKind.EnumStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ClassStatement,
SyntaxKind.ModuleStatement
Return DirectCast(node, TypeStatementSyntax).Identifier
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return DirectCast(node, DelegateStatementSyntax).Identifier
End Select
Throw ExceptionUtilities.UnexpectedValue(node)
End Function
Public Function GetIdentifierOfIdentifierName(node As SyntaxNode) As SyntaxToken Implements ISyntaxFacts.GetIdentifierOfIdentifierName
Return DirectCast(node, IdentifierNameSyntax).Identifier
End Function
Public Function IsDeclaratorOfLocalDeclarationStatement(declarator As SyntaxNode, localDeclarationStatement As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclaratorOfLocalDeclarationStatement
Return DirectCast(localDeclarationStatement, LocalDeclarationStatementSyntax).Declarators.
Contains(DirectCast(declarator, VariableDeclaratorSyntax))
End Function
Public Function AreEquivalent(token1 As SyntaxToken, token2 As SyntaxToken) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(token1, token2)
End Function
Public Function AreEquivalent(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Implements ISyntaxFacts.AreEquivalent
Return SyntaxFactory.AreEquivalent(node1, node2)
End Function
Public Function IsExpressionOfForeach(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExpressionOfForeach
Return node IsNot Nothing AndAlso TryCast(node.Parent, ForEachStatementSyntax)?.Expression Is node
End Function
Public Function GetExpressionOfExpressionStatement(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfExpressionStatement
Return DirectCast(node, ExpressionStatementSyntax).Expression
End Function
Public Function IsIsExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsExpression
Return node.IsKind(SyntaxKind.TypeOfIsExpression)
End Function
Public Function WalkDownParentheses(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.WalkDownParentheses
Return If(TryCast(node, ExpressionSyntax)?.WalkDownParentheses(), node)
End Function
Public Sub GetPartsOfTupleExpression(Of TArgumentSyntax As SyntaxNode)(
node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef arguments As SeparatedSyntaxList(Of TArgumentSyntax), ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfTupleExpression
Dim tupleExpr = DirectCast(node, TupleExpressionSyntax)
openParen = tupleExpr.OpenParenToken
arguments = CType(CType(tupleExpr.Arguments, SeparatedSyntaxList(Of SyntaxNode)), SeparatedSyntaxList(Of TArgumentSyntax))
closeParen = tupleExpr.CloseParenToken
End Sub
Private Function ISyntaxFacts_IsSingleLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineCommentTrivia
Return MyBase.IsSingleLineCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsMultiLineCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineCommentTrivia
Return MyBase.IsMultiLineCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsSingleLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsSingleLineDocCommentTrivia
Return MyBase.IsSingleLineDocCommentTrivia(trivia)
End Function
Private Function ISyntaxFacts_IsMultiLineDocCommentTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsMultiLineDocCommentTrivia
Return MyBase.IsMultiLineDocCommentTrivia(trivia)
Return False
End Function
Private Function ISyntaxFacts_IsShebangDirectiveTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsShebangDirectiveTrivia
Return MyBase.IsShebangDirectiveTrivia(trivia)
End Function
Public Overrides Function IsPreprocessorDirective(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsPreprocessorDirective
Return SyntaxFacts.IsPreprocessorDirective(trivia.Kind())
End Function
Public Function IsRegularComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsRegularComment
Return trivia.Kind = SyntaxKind.CommentTrivia
End Function
Public Function IsDocumentationComment(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationComment
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function
Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsElastic
Return trivia.IsElastic()
End Function
Public Function IsPragmaDirective(trivia As SyntaxTrivia, ByRef isDisable As Boolean, ByRef isActive As Boolean, ByRef errorCodes As SeparatedSyntaxList(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.IsPragmaDirective
Return trivia.IsPragmaDirective(isDisable, isActive, errorCodes)
End Function
Protected Overrides Function ContainsInterleavedDirective(span As TextSpan, token As SyntaxToken, cancellationToken As CancellationToken) As Boolean
Return token.ContainsInterleavedDirective(span, cancellationToken)
End Function
Private Function ISyntaxFacts_ContainsInterleavedDirective(node As SyntaxNode, cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return ContainsInterleavedDirective(node, cancellationToken)
End Function
Private Function ISyntaxFacts_ContainsInterleavedDirective1(nodes As ImmutableArray(Of SyntaxNode), cancellationToken As CancellationToken) As Boolean Implements ISyntaxFacts.ContainsInterleavedDirective
Return ContainsInterleavedDirective(nodes, cancellationToken)
End Function
Public Function IsDocumentationCommentExteriorTrivia(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFacts.IsDocumentationCommentExteriorTrivia
Return trivia.Kind() = SyntaxKind.DocumentationCommentExteriorTrivia
End Function
Public Function GetModifiers(node As SyntaxNode) As SyntaxTokenList Implements ISyntaxFacts.GetModifiers
Return node.GetModifiers()
End Function
Public Function WithModifiers(node As SyntaxNode, modifiers As SyntaxTokenList) As SyntaxNode Implements ISyntaxFacts.WithModifiers
Return node.WithModifiers(modifiers)
End Function
Public Function GetVariablesOfLocalDeclarationStatement(node As SyntaxNode) As SeparatedSyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetVariablesOfLocalDeclarationStatement
Return DirectCast(node, LocalDeclarationStatementSyntax).Declarators
End Function
Public Function GetInitializerOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetInitializerOfVariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Initializer
End Function
Public Function GetTypeOfVariableDeclarator(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfVariableDeclarator
Dim declarator = DirectCast(node, VariableDeclaratorSyntax)
Return TryCast(declarator.AsClause, SimpleAsClauseSyntax)?.Type
End Function
Public Function GetValueOfEqualsValueClause(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetValueOfEqualsValueClause
Return DirectCast(node, EqualsValueSyntax).Value
End Function
Public Function IsScopeBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsScopeBlock
' VB has no equivalent of curly braces.
Return False
End Function
Public Function IsExecutableBlock(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsExecutableBlock
Return node.IsExecutableBlock()
End Function
Public Function GetExecutableBlockStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetExecutableBlockStatements
Return node.GetExecutableBlockStatements()
End Function
Public Function FindInnermostCommonExecutableBlock(nodes As IEnumerable(Of SyntaxNode)) As SyntaxNode Implements ISyntaxFacts.FindInnermostCommonExecutableBlock
Return nodes.FindInnermostCommonExecutableBlock()
End Function
Public Function IsStatementContainer(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsStatementContainer
Return IsExecutableBlock(node)
End Function
Public Function GetStatementContainerStatements(node As SyntaxNode) As IReadOnlyList(Of SyntaxNode) Implements ISyntaxFacts.GetStatementContainerStatements
Return GetExecutableBlockStatements(node)
End Function
Public Function IsConversionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConversionExpression
Return node.Kind = SyntaxKind.CTypeExpression
End Function
Public Function IsCastExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsCastExpression
Return node.Kind = SyntaxKind.DirectCastExpression
End Function
Public Sub GetPartsOfCastExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef expression As SyntaxNode) Implements ISyntaxFacts.GetPartsOfCastExpression
Dim cast = DirectCast(node, DirectCastExpressionSyntax)
type = cast.Type
expression = cast.Expression
End Sub
Public Function GetDeconstructionReferenceLocation(node As SyntaxNode) As Location Implements ISyntaxFacts.GetDeconstructionReferenceLocation
Throw New NotImplementedException()
End Function
Public Function GetDeclarationIdentifierIfOverride(token As SyntaxToken) As SyntaxToken? Implements ISyntaxFacts.GetDeclarationIdentifierIfOverride
If token.Kind() = SyntaxKind.OverridesKeyword Then
Dim parent = token.Parent
Select Case parent.Kind()
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(parent, MethodStatementSyntax)
Return method.Identifier
Case SyntaxKind.PropertyStatement
Dim [property] = DirectCast(parent, PropertyStatementSyntax)
Return [property].Identifier
End Select
End If
Return Nothing
End Function
Public Shadows Function SpansPreprocessorDirective(nodes As IEnumerable(Of SyntaxNode)) As Boolean Implements ISyntaxFacts.SpansPreprocessorDirective
Return MyBase.SpansPreprocessorDirective(nodes)
End Function
Public Shadows Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean
Return MyBase.SpansPreprocessorDirective(tokens)
End Function
Public Function IsPostfixUnaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsPostfixUnaryExpression
' Does not exist in VB.
Return False
End Function
Public Function IsMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Function IsNameOfMemberBindingExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNameOfMemberBindingExpression
' Does not exist in VB. VB represents a member binding as a MemberAccessExpression with null target.
Return False
End Function
Public Overrides Function GetAttributeLists(node As SyntaxNode) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetAttributeLists
Return node.GetAttributeLists()
End Function
Public Function IsUsingAliasDirective(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUsingAliasDirective
Dim importStatement = TryCast(node, ImportsStatementSyntax)
If (importStatement IsNot Nothing) Then
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
Return True
End If
End If
Next
End If
Return False
End Function
Public Sub GetPartsOfUsingAliasDirective(
node As SyntaxNode,
ByRef globalKeyword As SyntaxToken,
ByRef [alias] As SyntaxToken,
ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUsingAliasDirective
Dim importStatement = DirectCast(node, ImportsStatementSyntax)
For Each importsClause In importStatement.ImportsClauses
If importsClause.Kind = SyntaxKind.SimpleImportsClause Then
Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax)
If simpleImportsClause.Alias IsNot Nothing Then
globalKeyword = Nothing
[alias] = simpleImportsClause.Alias.Identifier
name = simpleImportsClause.Name
Return
End If
End If
Next
Throw ExceptionUtilities.Unreachable
End Sub
Public Overrides Function IsParameterNameXmlElementSyntax(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParameterNameXmlElementSyntax
Dim xmlElement = TryCast(node, XmlElementSyntax)
If xmlElement IsNot Nothing Then
Dim name = TryCast(xmlElement.StartTag.Name, XmlNameSyntax)
Return name?.LocalName.ValueText = DocumentationCommentXmlNames.ParameterElementName
End If
Return False
End Function
Public Overrides Function GetContentFromDocumentationCommentTriviaSyntax(trivia As SyntaxTrivia) As SyntaxList(Of SyntaxNode) Implements ISyntaxFacts.GetContentFromDocumentationCommentTriviaSyntax
Dim documentationCommentTrivia = TryCast(trivia.GetStructure(), DocumentationCommentTriviaSyntax)
If documentationCommentTrivia IsNot Nothing Then
Return documentationCommentTrivia.Content
End If
Return Nothing
End Function
Friend Shared Function IsChildOf(node As SyntaxNode, kind As SyntaxKind) As Boolean
Return node.Parent IsNot Nothing AndAlso node.Parent.IsKind(kind)
End Function
Friend Shared Function IsChildOfVariableDeclaration(node As SyntaxNode) As Boolean
Return IsChildOf(node, SyntaxKind.FieldDeclaration) OrElse IsChildOf(node, SyntaxKind.LocalDeclarationStatement)
End Function
Private Shared Function GetDeclarationCount(nodes As IReadOnlyList(Of SyntaxNode)) As Integer
Dim count As Integer = 0
For i = 0 To nodes.Count - 1
count = count + GetDeclarationCount(nodes(i))
Next
Return count
End Function
Friend Shared Function GetDeclarationCount(node As SyntaxNode) As Integer
Select Case node.Kind
Case SyntaxKind.FieldDeclaration
Return GetDeclarationCount(DirectCast(node, FieldDeclarationSyntax).Declarators)
Case SyntaxKind.LocalDeclarationStatement
Return GetDeclarationCount(DirectCast(node, LocalDeclarationStatementSyntax).Declarators)
Case SyntaxKind.VariableDeclarator
Return DirectCast(node, VariableDeclaratorSyntax).Names.Count
Case SyntaxKind.AttributesStatement
Return GetDeclarationCount(DirectCast(node, AttributesStatementSyntax).AttributeLists)
Case SyntaxKind.AttributeList
Return DirectCast(node, AttributeListSyntax).Attributes.Count
Case SyntaxKind.ImportsStatement
Return DirectCast(node, ImportsStatementSyntax).ImportsClauses.Count
End Select
Return 1
End Function
Public Function SupportsNotPattern(options As ParseOptions) As Boolean Implements ISyntaxFacts.SupportsNotPattern
Return False
End Function
Public Function IsIsPatternExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsIsPatternExpression
Return False
End Function
Public Function IsAnyPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnyPattern
Return False
End Function
Public Function IsAndPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAndPattern
Return False
End Function
Public Function IsBinaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryPattern
Return False
End Function
Public Function IsConstantPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsConstantPattern
Return False
End Function
Public Function IsDeclarationPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsDeclarationPattern
Return False
End Function
Public Function IsNotPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsNotPattern
Return False
End Function
Public Function IsOrPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsOrPattern
Return False
End Function
Public Function IsParenthesizedPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsParenthesizedPattern
Return False
End Function
Public Function IsRecursivePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsRecursivePattern
Return False
End Function
Public Function IsUnaryPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsUnaryPattern
Return False
End Function
Public Function IsTypePattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsTypePattern
Return False
End Function
Public Function IsVarPattern(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVarPattern
Return False
End Function
Public Sub GetPartsOfIsPatternExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef isToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfIsPatternExpression
Throw ExceptionUtilities.Unreachable
End Sub
Public Function GetExpressionOfConstantPattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfConstantPattern
Throw ExceptionUtilities.Unreachable
End Function
Public Sub GetPartsOfParenthesizedPattern(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef pattern As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfBinaryPattern(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfUnaryPattern(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef pattern As SyntaxNode) Implements ISyntaxFacts.GetPartsOfUnaryPattern
Throw ExceptionUtilities.Unreachable
End Sub
Public Sub GetPartsOfDeclarationPattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfDeclarationPattern
Throw New NotImplementedException()
End Sub
Public Sub GetPartsOfRecursivePattern(node As SyntaxNode, ByRef type As SyntaxNode, ByRef positionalPart As SyntaxNode, ByRef propertyPart As SyntaxNode, ByRef designation As SyntaxNode) Implements ISyntaxFacts.GetPartsOfRecursivePattern
Throw New NotImplementedException()
End Sub
Public Function GetTypeOfTypePattern(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetTypeOfTypePattern
Throw New NotImplementedException()
End Function
Public Sub GetPartsOfInterpolationExpression(node As SyntaxNode, ByRef stringStartToken As SyntaxToken, ByRef contents As SyntaxList(Of SyntaxNode), ByRef stringEndToken As SyntaxToken) Implements ISyntaxFacts.GetPartsOfInterpolationExpression
Dim interpolatedStringExpressionSyntax As InterpolatedStringExpressionSyntax = DirectCast(node, InterpolatedStringExpressionSyntax)
stringStartToken = interpolatedStringExpressionSyntax.DollarSignDoubleQuoteToken
contents = interpolatedStringExpressionSyntax.Contents
stringEndToken = interpolatedStringExpressionSyntax.DoubleQuoteToken
End Sub
Public Function IsVerbatimInterpolatedStringExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsVerbatimInterpolatedStringExpression
Return False
End Function
#Region "IsXXX members"
Public Function IsAnonymousFunctionExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsAnonymousFunctionExpression
Return TypeOf node Is LambdaExpressionSyntax
End Function
Public Function IsBaseNamespaceDeclaration(<NotNullWhen(True)> node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBaseNamespaceDeclaration
Return TypeOf node Is NamespaceBlockSyntax
End Function
Public Function IsBinaryExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsBinaryExpression
Return TypeOf node Is BinaryExpressionSyntax
End Function
Public Function IsLiteralExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsLiteralExpression
Return TypeOf node Is LiteralExpressionSyntax
End Function
Public Function IsMemberAccessExpression(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsMemberAccessExpression
Return TypeOf node Is MemberAccessExpressionSyntax
End Function
Public Function IsSimpleName(node As SyntaxNode) As Boolean Implements ISyntaxFacts.IsSimpleName
Return TypeOf node Is SimpleNameSyntax
End Function
#End Region
#Region "GetPartsOfXXX members"
Public Sub GetPartsOfBinaryExpression(node As SyntaxNode, ByRef left As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfBinaryExpression
Dim binaryExpression = DirectCast(node, BinaryExpressionSyntax)
left = binaryExpression.Left
operatorToken = binaryExpression.OperatorToken
right = binaryExpression.Right
End Sub
Public Sub GetPartsOfCompilationUnit(node As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef attributeLists As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfCompilationUnit
Dim compilationUnit = DirectCast(node, CompilationUnitSyntax)
[imports] = compilationUnit.Imports
attributeLists = compilationUnit.Attributes
members = compilationUnit.Members
End Sub
Public Sub GetPartsOfConditionalAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef whenNotNull As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalAccessExpression
Dim conditionalAccess = DirectCast(node, ConditionalAccessExpressionSyntax)
expression = conditionalAccess.Expression
operatorToken = conditionalAccess.QuestionMarkToken
whenNotNull = conditionalAccess.WhenNotNull
End Sub
Public Sub GetPartsOfConditionalExpression(node As SyntaxNode, ByRef condition As SyntaxNode, ByRef whenTrue As SyntaxNode, ByRef whenFalse As SyntaxNode) Implements ISyntaxFacts.GetPartsOfConditionalExpression
Dim conditionalExpression = DirectCast(node, TernaryConditionalExpressionSyntax)
condition = conditionalExpression.Condition
whenTrue = conditionalExpression.WhenTrue
whenFalse = conditionalExpression.WhenFalse
End Sub
Public Sub GetPartsOfInvocationExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef argumentList As SyntaxNode) Implements ISyntaxFacts.GetPartsOfInvocationExpression
Dim invocation = DirectCast(node, InvocationExpressionSyntax)
expression = invocation.Expression
argumentList = invocation.ArgumentList
End Sub
Public Sub GetPartsOfMemberAccessExpression(node As SyntaxNode, ByRef expression As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef name As SyntaxNode) Implements ISyntaxFacts.GetPartsOfMemberAccessExpression
Dim memberAccess = DirectCast(node, MemberAccessExpressionSyntax)
expression = memberAccess.Expression
operatorToken = memberAccess.OperatorToken
name = memberAccess.Name
End Sub
Public Sub GetPartsOfBaseNamespaceDeclaration(node As SyntaxNode, ByRef name As SyntaxNode, ByRef [imports] As SyntaxList(Of SyntaxNode), ByRef members As SyntaxList(Of SyntaxNode)) Implements ISyntaxFacts.GetPartsOfBaseNamespaceDeclaration
Dim namespaceBlock = DirectCast(node, NamespaceBlockSyntax)
name = namespaceBlock.NamespaceStatement.Name
[imports] = Nothing
members = namespaceBlock.Members
End Sub
Public Sub GetPartsOfObjectCreationExpression(node As SyntaxNode, ByRef type As SyntaxNode, ByRef argumentList As SyntaxNode, ByRef initializer As SyntaxNode) Implements ISyntaxFacts.GetPartsOfObjectCreationExpression
Dim objectCreationExpression = DirectCast(node, ObjectCreationExpressionSyntax)
type = objectCreationExpression.Type
argumentList = objectCreationExpression.ArgumentList
initializer = objectCreationExpression.Initializer
End Sub
Public Sub GetPartsOfParenthesizedExpression(node As SyntaxNode, ByRef openParen As SyntaxToken, ByRef expression As SyntaxNode, ByRef closeParen As SyntaxToken) Implements ISyntaxFacts.GetPartsOfParenthesizedExpression
Dim parenthesizedExpression = DirectCast(node, ParenthesizedExpressionSyntax)
openParen = parenthesizedExpression.OpenParenToken
expression = parenthesizedExpression.Expression
closeParen = parenthesizedExpression.CloseParenToken
End Sub
Public Sub GetPartsOfPrefixUnaryExpression(node As SyntaxNode, ByRef operatorToken As SyntaxToken, ByRef operand As SyntaxNode) Implements ISyntaxFacts.GetPartsOfPrefixUnaryExpression
Dim unaryExpression = DirectCast(node, UnaryExpressionSyntax)
operatorToken = unaryExpression.OperatorToken
operand = unaryExpression.Operand
End Sub
Public Sub GetPartsOfQualifiedName(node As SyntaxNode, ByRef left As SyntaxNode, ByRef dotToken As SyntaxToken, ByRef right As SyntaxNode) Implements ISyntaxFacts.GetPartsOfQualifiedName
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
left = qualifiedName.Left
dotToken = qualifiedName.DotToken
right = qualifiedName.Right
End Sub
#End Region
#Region "GetXXXOfYYY members"
Public Function GetExpressionOfAwaitExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfAwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).Expression
End Function
Public Function GetExpressionOfThrowExpression(node As SyntaxNode) As SyntaxNode Implements ISyntaxFacts.GetExpressionOfThrowExpression
' ThrowExpression doesn't exist in VB
Throw New NotImplementedException()
End Function
#End Region
End Class
End Namespace
| 1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/SyntaxTokenExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery
{
internal static partial class SyntaxTokenExtensions
{
public static bool IsUsingOrExternKeyword(this SyntaxToken token)
{
return
token.Kind() == SyntaxKind.UsingKeyword ||
token.Kind() == SyntaxKind.ExternKeyword;
}
public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.UsingKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.UsingKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.StaticKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.StaticKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsBeginningOfStatementContext(this SyntaxToken token)
{
// cases:
// {
// |
// }
// |
// Note, the following is *not* a legal statement context:
// do { } |
// ...;
// |
// case 0:
// |
// default:
// |
// label:
// |
// if (goo)
// |
// while (true)
// |
// do
// |
// for (;;)
// |
// foreach (var v in c)
// |
// else
// |
// using (expr)
// |
// fixed (void* v = &expr)
// |
// lock (expr)
// |
// for ( ; ; Goo(), |
// After attribute lists on a statement:
// [Bar]
// |
switch (token.Kind())
{
case SyntaxKind.OpenBraceToken when token.Parent.IsKind(SyntaxKind.Block):
return true;
case SyntaxKind.SemicolonToken:
var statement = token.GetAncestor<StatementSyntax>();
return statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) &&
statement.GetLastToken(includeZeroWidth: true) == token;
case SyntaxKind.CloseBraceToken:
if (token.Parent.IsKind(SyntaxKind.Block))
{
if (token.Parent.Parent is StatementSyntax)
{
// Most blocks that are the child of statement are places
// that we can follow with another statement. i.e.:
// if { }
// while () { }
// There are two exceptions.
// try {}
// do {}
if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) &&
!token.Parent.IsParentKind(SyntaxKind.DoStatement))
{
return true;
}
}
else if (
token.Parent.IsParentKind(SyntaxKind.ElseClause) ||
token.Parent.IsParentKind(SyntaxKind.FinallyClause) ||
token.Parent.IsParentKind(SyntaxKind.CatchClause) ||
token.Parent.IsParentKind(SyntaxKind.SwitchSection))
{
return true;
}
}
if (token.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
return false;
case SyntaxKind.ColonToken:
return token.Parent.IsKind(SyntaxKind.CaseSwitchLabel,
SyntaxKind.DefaultSwitchLabel,
SyntaxKind.CasePatternSwitchLabel,
SyntaxKind.LabeledStatement);
case SyntaxKind.DoKeyword when token.Parent.IsKind(SyntaxKind.DoStatement):
return true;
case SyntaxKind.CloseParenToken:
var parent = token.Parent;
return parent.IsKind(SyntaxKind.ForStatement) ||
parent.IsKind(SyntaxKind.ForEachStatement) ||
parent.IsKind(SyntaxKind.ForEachVariableStatement) ||
parent.IsKind(SyntaxKind.WhileStatement) ||
parent.IsKind(SyntaxKind.IfStatement) ||
parent.IsKind(SyntaxKind.LockStatement) ||
parent.IsKind(SyntaxKind.UsingStatement) ||
parent.IsKind(SyntaxKind.FixedStatement);
case SyntaxKind.ElseKeyword:
return token.Parent.IsKind(SyntaxKind.ElseClause);
case SyntaxKind.CloseBracketToken:
if (token.Parent.IsKind(SyntaxKind.AttributeList))
{
// attributes can belong to a statement
var container = token.Parent.Parent;
if (container is StatementSyntax)
return true;
}
return false;
}
return false;
}
public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token)
{
// cases:
// }
// |
// ...;
// |
// extern alias Goo;
// using System;
// |
// [assembly: Goo]
// |
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
}
if (token.Kind() == SyntaxKind.SemicolonToken)
{
var globalStatement = token.GetAncestor<GlobalStatementSyntax>();
if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token)
return true;
if (token.Parent is FileScopedNamespaceDeclarationSyntax namespaceDeclaration && namespaceDeclaration.SemicolonToken == token)
return true;
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
if (token.Kind() == SyntaxKind.CloseBracketToken)
{
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token)
return true;
}
if (token.Parent.IsKind(SyntaxKind.AttributeList))
{
var container = token.Parent.Parent;
if (container is IncompleteMemberSyntax && container.Parent is CompilationUnitSyntax)
return true;
}
}
return false;
}
public static bool IsAfterPossibleCast(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CloseParenToken)
{
if (token.Parent.IsKind(SyntaxKind.CastExpression))
{
return true;
}
if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr))
{
var expr = parenExpr.Expression;
if (expr is TypeSyntax)
{
return true;
}
}
}
return false;
}
public static bool IsLastTokenOfQueryClause(this SyntaxToken token)
{
if (token.IsLastTokenOfNode<QueryClauseSyntax>())
{
return true;
}
if (token.Kind() == SyntaxKind.IdentifierToken &&
token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword)
{
return true;
}
return false;
}
public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken)
{
// cases:
// #if |
// #if goo || |
// #if goo && |
// #if ( |
// #if ! |
// Same for elif
if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null)
{
return false;
}
// #if
// #elif
if (targetToken.Kind() == SyntaxKind.IfKeyword ||
targetToken.Kind() == SyntaxKind.ElifKeyword)
{
return true;
}
// ( |
if (targetToken.Kind() == SyntaxKind.OpenParenToken &&
targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
{
return true;
}
// ! |
if (targetToken.Parent is PrefixUnaryExpressionSyntax prefix)
{
return prefix.OperatorToken == targetToken;
}
// a &&
// a ||
if (targetToken.Parent is BinaryExpressionSyntax binary)
{
return binary.OperatorToken == targetToken;
}
return false;
}
public static bool IsOrderByDirectionContext(this SyntaxToken targetToken)
{
// cases:
// orderby a |
// orderby a a|
// orderby a, b |
// orderby a, b a|
if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken))
{
return false;
}
var ordering = targetToken.GetAncestor<OrderingSyntax>();
if (ordering == null)
{
return false;
}
// orderby a |
// orderby a, b |
var lastToken = ordering.Expression.GetLastToken(includeSkipped: true);
if (targetToken == lastToken)
{
return true;
}
return false;
}
public static bool IsSwitchLabelContext(this SyntaxToken targetToken)
{
// cases:
// case X: |
// default: |
// switch (e) { |
//
// case X: Statement(); |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.ColonToken)
{
if (targetToken.Parent.IsKind(
SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.CasePatternSwitchLabel))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.SemicolonToken ||
targetToken.Kind() == SyntaxKind.CloseBraceToken)
{
var section = targetToken.GetAncestor<SwitchSectionSyntax>();
if (section != null)
{
foreach (var statement in section.Statements)
{
if (targetToken == statement.GetLastToken(includeSkipped: true))
{
return true;
}
}
}
}
return false;
}
public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken)
{
return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken)
&& targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList);
}
public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken)
{
// cases:
// Goo( |
// Goo(expr, |
// Goo(bar: |
// new Goo( |
// new Goo(expr, |
// new Goo(bar: |
// Goo : base( |
// Goo : base(bar: |
// Goo : this( |
// Goo : this(bar: |
// Goo(bar: |
if (targetToken.Kind() == SyntaxKind.ColonToken &&
targetToken.Parent.IsKind(SyntaxKind.NameColon) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.Argument) &&
targetToken.Parent.Parent.Parent.IsKind(SyntaxKind.ArgumentList))
{
var owner = targetToken.Parent.Parent.Parent.Parent;
if (owner.IsKind(SyntaxKind.InvocationExpression) ||
owner.IsKind(SyntaxKind.ObjectCreationExpression) ||
owner.IsKind(SyntaxKind.BaseConstructorInitializer) ||
owner.IsKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.OpenParenToken ||
targetToken.Kind() == SyntaxKind.CommaToken)
{
if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList))
{
if (targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) ||
targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
// var( |
// var(expr, |
// Those are more likely to be deconstruction-declarations being typed than invocations a method "var"
if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) && !targetToken.IsInvocationOfVarExpression())
{
return true;
}
}
}
return false;
}
public static bool IsUnaryOperatorContext(this SyntaxToken targetToken)
{
if (targetToken.Kind() == SyntaxKind.OperatorKeyword &&
targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>())
{
return true;
}
return false;
}
public static bool IsUnsafeContext(this SyntaxToken targetToken)
{
return
targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) ||
targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsAfterYieldKeyword(this SyntaxToken targetToken)
{
// yield |
// yield r|
return targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword);
}
public static bool IsAnyAccessorDeclarationContext(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
{
return targetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, kind) ||
targetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, kind) ||
targetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, kind);
}
public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
where TMemberNode : SyntaxNode
{
if (!IsAccessorDeclarationContextWorker(ref targetToken))
{
return false;
}
var list = targetToken.GetAncestor<AccessorListSyntax>();
if (list == null)
{
return false;
}
// Check if we already have this accessor. (however, don't count it
// if the user is *on* that accessor.
var existingAccessor = list.Accessors
.Select(a => a.Keyword)
.FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind));
if (existingAccessor.Kind() != SyntaxKind.None)
{
var existingAccessorSpan = existingAccessor.Span;
if (!existingAccessorSpan.IntersectsWith(position))
{
return false;
}
}
var decl = targetToken.GetAncestor<TMemberNode>();
return decl != null;
}
private static bool IsAccessorDeclarationContextWorker(ref SyntaxToken targetToken)
{
// cases:
// int Goo { |
// int Goo { private |
// int Goo { set { } |
// int Goo { set; |
// int Goo { [Bar]|
// int Goo { readonly |
// Consume all preceding access modifiers
while (targetToken.Kind() == SyntaxKind.InternalKeyword ||
targetToken.Kind() == SyntaxKind.PublicKeyword ||
targetToken.Kind() == SyntaxKind.ProtectedKeyword ||
targetToken.Kind() == SyntaxKind.PrivateKeyword ||
targetToken.Kind() == SyntaxKind.ReadOnlyKeyword)
{
targetToken = targetToken.GetPreviousToken(includeSkipped: true);
}
// int Goo { |
// int Goo { private |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.AccessorList))
{
return true;
}
// int Goo { set { } |
// int Goo { set { } private |
if (targetToken.Kind() == SyntaxKind.CloseBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.Block) &&
targetToken.Parent.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Goo { set; |
if (targetToken.Kind() == SyntaxKind.SemicolonToken &&
targetToken.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Goo { [Bar]|
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.Parent is AccessorDeclarationSyntax)
{
return true;
}
return false;
}
private static bool IsGenericInterfaceOrDelegateTypeParameterList([NotNullWhen(true)] SyntaxNode? node)
{
if (node.IsKind(SyntaxKind.TypeParameterList))
{
if (node.IsParentKind(SyntaxKind.InterfaceDeclaration, out TypeDeclarationSyntax? typeDecl))
return typeDecl.TypeParameterList == node;
else if (node.IsParentKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl))
return delegateDecl.TypeParameterList == node;
}
return false;
}
public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken)
{
// cases:
// interface IGoo<|
// interface IGoo<A,|
// interface IGoo<[Bar]|
// delegate X D<|
// delegate X D<A,|
// delegate X D<[Bar]|
if (targetToken.Kind() == SyntaxKind.LessThanToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CommaToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.TypeParameter) &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.Parent.Parent))
{
return true;
}
return false;
}
public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax)
{
var argumentList = (BaseArgumentListSyntax)token.Parent;
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
if (item.AsNode() is ArgumentSyntax node && node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
public static bool IsNumericTypeContext(this SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (token.Parent is not MemberAccessExpressionSyntax memberAccessExpression)
{
return false;
}
var typeInfo = semanticModel.GetTypeInfo(memberAccessExpression.Expression, cancellationToken);
return typeInfo.Type.IsNumericType();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery
{
internal static partial class SyntaxTokenExtensions
{
public static bool IsUsingOrExternKeyword(this SyntaxToken token)
{
return
token.Kind() == SyntaxKind.UsingKeyword ||
token.Kind() == SyntaxKind.ExternKeyword;
}
public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.UsingKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.UsingKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.StaticKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.StaticKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsBeginningOfStatementContext(this SyntaxToken token)
{
// cases:
// {
// |
// }
// |
// Note, the following is *not* a legal statement context:
// do { } |
// ...;
// |
// case 0:
// |
// default:
// |
// label:
// |
// if (goo)
// |
// while (true)
// |
// do
// |
// for (;;)
// |
// foreach (var v in c)
// |
// else
// |
// using (expr)
// |
// fixed (void* v = &expr)
// |
// lock (expr)
// |
// for ( ; ; Goo(), |
// After attribute lists on a statement:
// [Bar]
// |
switch (token.Kind())
{
case SyntaxKind.OpenBraceToken when token.Parent.IsKind(SyntaxKind.Block):
return true;
case SyntaxKind.SemicolonToken:
var statement = token.GetAncestor<StatementSyntax>();
return statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) &&
statement.GetLastToken(includeZeroWidth: true) == token;
case SyntaxKind.CloseBraceToken:
if (token.Parent.IsKind(SyntaxKind.Block))
{
if (token.Parent.Parent is StatementSyntax)
{
// Most blocks that are the child of statement are places
// that we can follow with another statement. i.e.:
// if { }
// while () { }
// There are two exceptions.
// try {}
// do {}
if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) &&
!token.Parent.IsParentKind(SyntaxKind.DoStatement))
{
return true;
}
}
else if (
token.Parent.IsParentKind(SyntaxKind.ElseClause) ||
token.Parent.IsParentKind(SyntaxKind.FinallyClause) ||
token.Parent.IsParentKind(SyntaxKind.CatchClause) ||
token.Parent.IsParentKind(SyntaxKind.SwitchSection))
{
return true;
}
}
if (token.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
return false;
case SyntaxKind.ColonToken:
return token.Parent.IsKind(SyntaxKind.CaseSwitchLabel,
SyntaxKind.DefaultSwitchLabel,
SyntaxKind.CasePatternSwitchLabel,
SyntaxKind.LabeledStatement);
case SyntaxKind.DoKeyword when token.Parent.IsKind(SyntaxKind.DoStatement):
return true;
case SyntaxKind.CloseParenToken:
var parent = token.Parent;
return parent.IsKind(SyntaxKind.ForStatement) ||
parent.IsKind(SyntaxKind.ForEachStatement) ||
parent.IsKind(SyntaxKind.ForEachVariableStatement) ||
parent.IsKind(SyntaxKind.WhileStatement) ||
parent.IsKind(SyntaxKind.IfStatement) ||
parent.IsKind(SyntaxKind.LockStatement) ||
parent.IsKind(SyntaxKind.UsingStatement) ||
parent.IsKind(SyntaxKind.FixedStatement);
case SyntaxKind.ElseKeyword:
return token.Parent.IsKind(SyntaxKind.ElseClause);
case SyntaxKind.CloseBracketToken:
if (token.Parent.IsKind(SyntaxKind.AttributeList))
{
// attributes can belong to a statement
var container = token.Parent.Parent;
if (container is StatementSyntax)
return true;
}
return false;
}
return false;
}
public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token)
{
// cases:
// }
// |
// ...;
// |
// extern alias Goo;
// using System;
// |
// [assembly: Goo]
// |
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
}
if (token.Kind() == SyntaxKind.SemicolonToken)
{
var globalStatement = token.GetAncestor<GlobalStatementSyntax>();
if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token)
return true;
if (token.Parent is FileScopedNamespaceDeclarationSyntax namespaceDeclaration && namespaceDeclaration.SemicolonToken == token)
return true;
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
if (token.Kind() == SyntaxKind.CloseBracketToken)
{
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token)
return true;
}
if (token.Parent.IsKind(SyntaxKind.AttributeList))
{
var container = token.Parent.Parent;
if (container is IncompleteMemberSyntax && container.Parent is CompilationUnitSyntax)
return true;
}
}
return false;
}
public static bool IsAfterPossibleCast(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CloseParenToken)
{
if (token.Parent.IsKind(SyntaxKind.CastExpression))
{
return true;
}
if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr))
{
var expr = parenExpr.Expression;
if (expr is TypeSyntax)
{
return true;
}
}
}
return false;
}
public static bool IsLastTokenOfQueryClause(this SyntaxToken token)
{
if (token.IsLastTokenOfNode<QueryClauseSyntax>())
{
return true;
}
if (token.Kind() == SyntaxKind.IdentifierToken &&
token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword)
{
return true;
}
return false;
}
public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken)
{
// cases:
// #if |
// #if goo || |
// #if goo && |
// #if ( |
// #if ! |
// Same for elif
if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null)
{
return false;
}
// #if
// #elif
if (targetToken.Kind() == SyntaxKind.IfKeyword ||
targetToken.Kind() == SyntaxKind.ElifKeyword)
{
return true;
}
// ( |
if (targetToken.Kind() == SyntaxKind.OpenParenToken &&
targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
{
return true;
}
// ! |
if (targetToken.Parent is PrefixUnaryExpressionSyntax prefix)
{
return prefix.OperatorToken == targetToken;
}
// a &&
// a ||
if (targetToken.Parent is BinaryExpressionSyntax binary)
{
return binary.OperatorToken == targetToken;
}
return false;
}
public static bool IsOrderByDirectionContext(this SyntaxToken targetToken)
{
// cases:
// orderby a |
// orderby a a|
// orderby a, b |
// orderby a, b a|
if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken))
{
return false;
}
var ordering = targetToken.GetAncestor<OrderingSyntax>();
if (ordering == null)
{
return false;
}
// orderby a |
// orderby a, b |
var lastToken = ordering.Expression.GetLastToken(includeSkipped: true);
if (targetToken == lastToken)
{
return true;
}
return false;
}
public static bool IsSwitchLabelContext(this SyntaxToken targetToken)
{
// cases:
// case X: |
// default: |
// switch (e) { |
//
// case X: Statement(); |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.ColonToken)
{
if (targetToken.Parent.IsKind(
SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.CasePatternSwitchLabel))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.SemicolonToken ||
targetToken.Kind() == SyntaxKind.CloseBraceToken)
{
var section = targetToken.GetAncestor<SwitchSectionSyntax>();
if (section != null)
{
foreach (var statement in section.Statements)
{
if (targetToken == statement.GetLastToken(includeSkipped: true))
{
return true;
}
}
}
}
return false;
}
public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken)
{
return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken)
&& targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList);
}
public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken)
{
// cases:
// Goo( |
// Goo(expr, |
// Goo(bar: |
// new Goo( |
// new Goo(expr, |
// new Goo(bar: |
// Goo : base( |
// Goo : base(bar: |
// Goo : this( |
// Goo : this(bar: |
// Goo(bar: |
if (targetToken.Kind() == SyntaxKind.ColonToken &&
targetToken.Parent.IsKind(SyntaxKind.NameColon) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.Argument) &&
targetToken.Parent.Parent.Parent.IsKind(SyntaxKind.ArgumentList))
{
var owner = targetToken.Parent.Parent.Parent.Parent;
if (owner.IsKind(SyntaxKind.InvocationExpression) ||
owner.IsKind(SyntaxKind.ObjectCreationExpression) ||
owner.IsKind(SyntaxKind.BaseConstructorInitializer) ||
owner.IsKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.OpenParenToken ||
targetToken.Kind() == SyntaxKind.CommaToken)
{
if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList))
{
if (targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) ||
targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
// var( |
// var(expr, |
// Those are more likely to be deconstruction-declarations being typed than invocations a method "var"
if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) && !targetToken.IsInvocationOfVarExpression())
{
return true;
}
}
}
return false;
}
public static bool IsUnaryOperatorContext(this SyntaxToken targetToken)
{
if (targetToken.Kind() == SyntaxKind.OperatorKeyword &&
targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>())
{
return true;
}
return false;
}
public static bool IsUnsafeContext(this SyntaxToken targetToken)
{
return
targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) ||
targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsAfterYieldKeyword(this SyntaxToken targetToken)
{
// yield |
// yield r|
return targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword);
}
public static bool IsAnyAccessorDeclarationContext(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
{
return targetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, kind) ||
targetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, kind) ||
targetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, kind);
}
public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
where TMemberNode : SyntaxNode
{
if (!IsAccessorDeclarationContextWorker(ref targetToken))
{
return false;
}
var list = targetToken.GetAncestor<AccessorListSyntax>();
if (list == null)
{
return false;
}
// Check if we already have this accessor. (however, don't count it
// if the user is *on* that accessor.
var existingAccessor = list.Accessors
.Select(a => a.Keyword)
.FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind));
if (existingAccessor.Kind() != SyntaxKind.None)
{
var existingAccessorSpan = existingAccessor.Span;
if (!existingAccessorSpan.IntersectsWith(position))
{
return false;
}
}
var decl = targetToken.GetAncestor<TMemberNode>();
return decl != null;
}
private static bool IsAccessorDeclarationContextWorker(ref SyntaxToken targetToken)
{
// cases:
// int Goo { |
// int Goo { private |
// int Goo { set { } |
// int Goo { set; |
// int Goo { [Bar]|
// int Goo { readonly |
// Consume all preceding access modifiers
while (targetToken.Kind() == SyntaxKind.InternalKeyword ||
targetToken.Kind() == SyntaxKind.PublicKeyword ||
targetToken.Kind() == SyntaxKind.ProtectedKeyword ||
targetToken.Kind() == SyntaxKind.PrivateKeyword ||
targetToken.Kind() == SyntaxKind.ReadOnlyKeyword)
{
targetToken = targetToken.GetPreviousToken(includeSkipped: true);
}
// int Goo { |
// int Goo { private |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.AccessorList))
{
return true;
}
// int Goo { set { } |
// int Goo { set { } private |
if (targetToken.Kind() == SyntaxKind.CloseBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.Block) &&
targetToken.Parent.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Goo { set; |
if (targetToken.Kind() == SyntaxKind.SemicolonToken &&
targetToken.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Goo { [Bar]|
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.Parent is AccessorDeclarationSyntax)
{
return true;
}
return false;
}
private static bool IsGenericInterfaceOrDelegateTypeParameterList([NotNullWhen(true)] SyntaxNode? node)
{
if (node.IsKind(SyntaxKind.TypeParameterList))
{
if (node.IsParentKind(SyntaxKind.InterfaceDeclaration, out TypeDeclarationSyntax? typeDecl))
return typeDecl.TypeParameterList == node;
else if (node.IsParentKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl))
return delegateDecl.TypeParameterList == node;
}
return false;
}
public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken)
{
// cases:
// interface IGoo<|
// interface IGoo<A,|
// interface IGoo<[Bar]|
// delegate X D<|
// delegate X D<A,|
// delegate X D<[Bar]|
if (targetToken.Kind() == SyntaxKind.LessThanToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CommaToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.TypeParameter) &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.Parent.Parent))
{
return true;
}
return false;
}
public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax)
{
var argumentList = (BaseArgumentListSyntax)token.Parent;
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
if (item.AsNode() is ArgumentSyntax node && node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
public static bool IsNumericTypeContext(this SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (token.Parent is not MemberAccessExpressionSyntax memberAccessExpression)
{
return false;
}
var typeInfo = semanticModel.GetTypeInfo(memberAccessExpression.Expression, cancellationToken);
return typeInfo.Type.IsNumericType();
}
public static bool IsTypeNamedDynamic(this SyntaxToken token)
=> token.Parent is IdentifierNameSyntax typedParent &&
SyntaxFacts.IsInTypeOnlyContext(typedParent) &&
token.Text == "dynamic";
}
}
| 1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.IPragmaBasedCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal partial class AbstractSuppressionCodeFixProvider
{
/// <summary>
/// Suppression code action based on pragma add/remove/edit.
/// </summary>
internal interface IPragmaBasedCodeAction
{
Task<Document> GetChangedDocumentAsync(bool includeStartTokenChange, bool includeEndTokenChange, CancellationToken cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal partial class AbstractSuppressionCodeFixProvider
{
/// <summary>
/// Suppression code action based on pragma add/remove/edit.
/// </summary>
internal interface IPragmaBasedCodeAction
{
Task<Document> GetChangedDocumentAsync(bool includeStartTokenChange, bool includeEndTokenChange, CancellationToken cancellationToken);
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Features/VisualBasic/Portable/CodeRefactorings/AddMissingImports/VisualBasicAddMissingImportsRefactoringProvider.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.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.AddMissingImports
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.PasteTracking
Imports Microsoft.CodeAnalysis.VisualBasic
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.AddMissingImports), [Shared]>
Friend Class VisualBasicAddMissingImportsRefactoringProvider
Inherits AbstractAddMissingImportsRefactoringProvider
Protected Overrides ReadOnly Property CodeActionTitle As String = VBFeaturesResources.Add_missing_Imports
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(pasteTrackingService As IPasteTrackingService)
MyBase.New(pasteTrackingService)
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.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.AddMissingImports
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.PasteTracking
Imports Microsoft.CodeAnalysis.VisualBasic
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.AddMissingImports), [Shared]>
Friend Class VisualBasicAddMissingImportsRefactoringProvider
Inherits AbstractAddMissingImportsRefactoringProvider
Protected Overrides ReadOnly Property CodeActionTitle As String = VBFeaturesResources.Add_missing_Imports
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(pasteTrackingService As IPasteTrackingService)
MyBase.New(pasteTrackingService)
End Sub
End Class
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList.WithThreeChildren.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax
{
internal partial class SyntaxList
{
internal class WithThreeChildren : SyntaxList
{
static WithThreeChildren()
{
ObjectBinder.RegisterTypeReader(typeof(WithThreeChildren), r => new WithThreeChildren(r));
}
private readonly GreenNode _child0;
private readonly GreenNode _child1;
private readonly GreenNode _child2;
internal WithThreeChildren(GreenNode child0, GreenNode child1, GreenNode child2)
{
this.SlotCount = 3;
this.AdjustFlagsAndWidth(child0);
_child0 = child0;
this.AdjustFlagsAndWidth(child1);
_child1 = child1;
this.AdjustFlagsAndWidth(child2);
_child2 = child2;
}
internal WithThreeChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, GreenNode child0, GreenNode child1, GreenNode child2)
: base(diagnostics, annotations)
{
this.SlotCount = 3;
this.AdjustFlagsAndWidth(child0);
_child0 = child0;
this.AdjustFlagsAndWidth(child1);
_child1 = child1;
this.AdjustFlagsAndWidth(child2);
_child2 = child2;
}
internal WithThreeChildren(ObjectReader reader)
: base(reader)
{
this.SlotCount = 3;
_child0 = (GreenNode)reader.ReadValue();
this.AdjustFlagsAndWidth(_child0);
_child1 = (GreenNode)reader.ReadValue();
this.AdjustFlagsAndWidth(_child1);
_child2 = (GreenNode)reader.ReadValue();
this.AdjustFlagsAndWidth(_child2);
}
internal override void WriteTo(ObjectWriter writer)
{
base.WriteTo(writer);
writer.WriteValue(_child0);
writer.WriteValue(_child1);
writer.WriteValue(_child2);
}
internal override GreenNode? GetSlot(int index)
{
switch (index)
{
case 0:
return _child0;
case 1:
return _child1;
case 2:
return _child2;
default:
return null;
}
}
internal override void CopyTo(ArrayElement<GreenNode>[] array, int offset)
{
array[offset].Value = _child0;
array[offset + 1].Value = _child1;
array[offset + 2].Value = _child2;
}
internal override SyntaxNode CreateRed(SyntaxNode? parent, int position)
{
return new Syntax.SyntaxList.WithThreeChildren(this, parent, position);
}
internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors)
{
return new WithThreeChildren(errors, this.GetAnnotations(), _child0, _child1, _child2);
}
internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations)
{
return new WithThreeChildren(GetDiagnostics(), annotations, _child0, _child1, _child2);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax
{
internal partial class SyntaxList
{
internal class WithThreeChildren : SyntaxList
{
static WithThreeChildren()
{
ObjectBinder.RegisterTypeReader(typeof(WithThreeChildren), r => new WithThreeChildren(r));
}
private readonly GreenNode _child0;
private readonly GreenNode _child1;
private readonly GreenNode _child2;
internal WithThreeChildren(GreenNode child0, GreenNode child1, GreenNode child2)
{
this.SlotCount = 3;
this.AdjustFlagsAndWidth(child0);
_child0 = child0;
this.AdjustFlagsAndWidth(child1);
_child1 = child1;
this.AdjustFlagsAndWidth(child2);
_child2 = child2;
}
internal WithThreeChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, GreenNode child0, GreenNode child1, GreenNode child2)
: base(diagnostics, annotations)
{
this.SlotCount = 3;
this.AdjustFlagsAndWidth(child0);
_child0 = child0;
this.AdjustFlagsAndWidth(child1);
_child1 = child1;
this.AdjustFlagsAndWidth(child2);
_child2 = child2;
}
internal WithThreeChildren(ObjectReader reader)
: base(reader)
{
this.SlotCount = 3;
_child0 = (GreenNode)reader.ReadValue();
this.AdjustFlagsAndWidth(_child0);
_child1 = (GreenNode)reader.ReadValue();
this.AdjustFlagsAndWidth(_child1);
_child2 = (GreenNode)reader.ReadValue();
this.AdjustFlagsAndWidth(_child2);
}
internal override void WriteTo(ObjectWriter writer)
{
base.WriteTo(writer);
writer.WriteValue(_child0);
writer.WriteValue(_child1);
writer.WriteValue(_child2);
}
internal override GreenNode? GetSlot(int index)
{
switch (index)
{
case 0:
return _child0;
case 1:
return _child1;
case 2:
return _child2;
default:
return null;
}
}
internal override void CopyTo(ArrayElement<GreenNode>[] array, int offset)
{
array[offset].Value = _child0;
array[offset + 1].Value = _child1;
array[offset + 2].Value = _child2;
}
internal override SyntaxNode CreateRed(SyntaxNode? parent, int position)
{
return new Syntax.SyntaxList.WithThreeChildren(this, parent, position);
}
internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors)
{
return new WithThreeChildren(errors, this.GetAnnotations(), _child0, _child1, _child2);
}
internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations)
{
return new WithThreeChildren(GetDiagnostics(), annotations, _child0, _child1, _child2);
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Dependencies/Collections/ImmutableSegmentedList.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
namespace Microsoft.CodeAnalysis.Collections
{
internal static class ImmutableSegmentedList
{
/// <inheritdoc cref="ImmutableList.Create{T}()"/>
public static ImmutableSegmentedList<T> Create<T>()
=> ImmutableSegmentedList<T>.Empty;
/// <inheritdoc cref="ImmutableList.Create{T}(T)"/>
public static ImmutableSegmentedList<T> Create<T>(T item)
=> ImmutableSegmentedList<T>.Empty.Add(item);
/// <inheritdoc cref="ImmutableList.Create{T}(T[])"/>
public static ImmutableSegmentedList<T> Create<T>(params T[] items)
=> ImmutableSegmentedList<T>.Empty.AddRange(items);
/// <inheritdoc cref="ImmutableList.CreateBuilder{T}()"/>
public static ImmutableSegmentedList<T>.Builder CreateBuilder<T>()
=> ImmutableSegmentedList<T>.Empty.ToBuilder();
/// <inheritdoc cref="ImmutableList.CreateRange{T}(IEnumerable{T})"/>
public static ImmutableSegmentedList<T> CreateRange<T>(IEnumerable<T> items)
=> ImmutableSegmentedList<T>.Empty.AddRange(items);
/// <inheritdoc cref="ImmutableList.ToImmutableList{TSource}(IEnumerable{TSource})"/>
public static ImmutableSegmentedList<T> ToImmutableSegmentedList<T>(this IEnumerable<T> source)
{
if (source is ImmutableSegmentedList<T> existingList)
return existingList;
return ImmutableSegmentedList<T>.Empty.AddRange(source);
}
/// <inheritdoc cref="ImmutableList.ToImmutableList{TSource}(ImmutableList{TSource}.Builder)"/>
public static ImmutableSegmentedList<T> ToImmutableSegmentedList<T>(this ImmutableSegmentedList<T>.Builder builder)
{
if (builder is null)
throw new ArgumentNullException(nameof(builder));
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;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Collections
{
internal static class ImmutableSegmentedList
{
/// <inheritdoc cref="ImmutableList.Create{T}()"/>
public static ImmutableSegmentedList<T> Create<T>()
=> ImmutableSegmentedList<T>.Empty;
/// <inheritdoc cref="ImmutableList.Create{T}(T)"/>
public static ImmutableSegmentedList<T> Create<T>(T item)
=> ImmutableSegmentedList<T>.Empty.Add(item);
/// <inheritdoc cref="ImmutableList.Create{T}(T[])"/>
public static ImmutableSegmentedList<T> Create<T>(params T[] items)
=> ImmutableSegmentedList<T>.Empty.AddRange(items);
/// <inheritdoc cref="ImmutableList.CreateBuilder{T}()"/>
public static ImmutableSegmentedList<T>.Builder CreateBuilder<T>()
=> ImmutableSegmentedList<T>.Empty.ToBuilder();
/// <inheritdoc cref="ImmutableList.CreateRange{T}(IEnumerable{T})"/>
public static ImmutableSegmentedList<T> CreateRange<T>(IEnumerable<T> items)
=> ImmutableSegmentedList<T>.Empty.AddRange(items);
/// <inheritdoc cref="ImmutableList.ToImmutableList{TSource}(IEnumerable{TSource})"/>
public static ImmutableSegmentedList<T> ToImmutableSegmentedList<T>(this IEnumerable<T> source)
{
if (source is ImmutableSegmentedList<T> existingList)
return existingList;
return ImmutableSegmentedList<T>.Empty.AddRange(source);
}
/// <inheritdoc cref="ImmutableList.ToImmutableList{TSource}(ImmutableList{TSource}.Builder)"/>
public static ImmutableSegmentedList<T> ToImmutableSegmentedList<T>(this ImmutableSegmentedList<T>.Builder builder)
{
if (builder is null)
throw new ArgumentNullException(nameof(builder));
return builder.ToImmutable();
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NoOpFormattingRule.cs | // Licensed to the .NET Foundation under one or more 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.Formatting.Rules
{
internal sealed class NoOpFormattingRule : AbstractFormattingRule
{
public static readonly NoOpFormattingRule Instance = new();
private NoOpFormattingRule()
{
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Formatting.Rules
{
internal sealed class NoOpFormattingRule : AbstractFormattingRule
{
public static readonly NoOpFormattingRule Instance = new();
private NoOpFormattingRule()
{
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Features/CSharp/Portable/Structure/CSharpBlockStructureProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class CSharpBlockStructureProvider : AbstractBlockStructureProvider
{
private static ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> CreateDefaultNodeProviderMap()
{
var builder = ImmutableDictionary.CreateBuilder<Type, ImmutableArray<AbstractSyntaxStructureProvider>>();
builder.Add<AccessorDeclarationSyntax, AccessorDeclarationStructureProvider>();
builder.Add<AnonymousMethodExpressionSyntax, AnonymousMethodExpressionStructureProvider>();
builder.Add<ArrowExpressionClauseSyntax, ArrowExpressionClauseStructureProvider>();
builder.Add<BlockSyntax, BlockSyntaxStructureProvider>();
builder.Add<ClassDeclarationSyntax, TypeDeclarationStructureProvider>();
builder.Add<CompilationUnitSyntax, CompilationUnitStructureProvider>();
builder.Add<ConstructorDeclarationSyntax, ConstructorDeclarationStructureProvider>();
builder.Add<ConversionOperatorDeclarationSyntax, ConversionOperatorDeclarationStructureProvider>();
builder.Add<DelegateDeclarationSyntax, DelegateDeclarationStructureProvider>();
builder.Add<DestructorDeclarationSyntax, DestructorDeclarationStructureProvider>();
builder.Add<DocumentationCommentTriviaSyntax, DocumentationCommentStructureProvider>();
builder.Add<EnumDeclarationSyntax, EnumDeclarationStructureProvider>();
builder.Add<EnumMemberDeclarationSyntax, EnumMemberDeclarationStructureProvider>();
builder.Add<EventDeclarationSyntax, EventDeclarationStructureProvider>();
builder.Add<EventFieldDeclarationSyntax, EventFieldDeclarationStructureProvider>();
builder.Add<FieldDeclarationSyntax, FieldDeclarationStructureProvider>();
builder.Add<IndexerDeclarationSyntax, IndexerDeclarationStructureProvider>();
builder.Add<InitializerExpressionSyntax, InitializerExpressionStructureProvider>();
builder.Add<InterfaceDeclarationSyntax, TypeDeclarationStructureProvider>();
builder.Add<MethodDeclarationSyntax, MethodDeclarationStructureProvider>();
builder.Add<NamespaceDeclarationSyntax, NamespaceDeclarationStructureProvider>();
builder.Add<OperatorDeclarationSyntax, OperatorDeclarationStructureProvider>();
builder.Add<ParenthesizedLambdaExpressionSyntax, ParenthesizedLambdaExpressionStructureProvider>();
builder.Add<PropertyDeclarationSyntax, PropertyDeclarationStructureProvider>();
builder.Add<RecordDeclarationSyntax, TypeDeclarationStructureProvider>();
builder.Add<RegionDirectiveTriviaSyntax, RegionDirectiveStructureProvider>();
builder.Add<SimpleLambdaExpressionSyntax, SimpleLambdaExpressionStructureProvider>();
builder.Add<StructDeclarationSyntax, TypeDeclarationStructureProvider>();
builder.Add<SwitchStatementSyntax, SwitchStatementStructureProvider>();
builder.Add<LiteralExpressionSyntax, StringLiteralExpressionStructureProvider>();
builder.Add<InterpolatedStringExpressionSyntax, InterpolatedStringExpressionStructureProvider>();
return builder.ToImmutable();
}
private static ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> CreateDefaultTriviaProviderMap()
{
var builder = ImmutableDictionary.CreateBuilder<int, ImmutableArray<AbstractSyntaxStructureProvider>>();
builder.Add((int)SyntaxKind.DisabledTextTrivia, ImmutableArray.Create<AbstractSyntaxStructureProvider>(new DisabledTextTriviaStructureProvider()));
return builder.ToImmutable();
}
internal CSharpBlockStructureProvider()
: base(CreateDefaultNodeProviderMap(), CreateDefaultTriviaProviderMap())
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class CSharpBlockStructureProvider : AbstractBlockStructureProvider
{
private static ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> CreateDefaultNodeProviderMap()
{
var builder = ImmutableDictionary.CreateBuilder<Type, ImmutableArray<AbstractSyntaxStructureProvider>>();
builder.Add<AccessorDeclarationSyntax, AccessorDeclarationStructureProvider>();
builder.Add<AnonymousMethodExpressionSyntax, AnonymousMethodExpressionStructureProvider>();
builder.Add<ArrowExpressionClauseSyntax, ArrowExpressionClauseStructureProvider>();
builder.Add<BlockSyntax, BlockSyntaxStructureProvider>();
builder.Add<ClassDeclarationSyntax, TypeDeclarationStructureProvider>();
builder.Add<CompilationUnitSyntax, CompilationUnitStructureProvider>();
builder.Add<ConstructorDeclarationSyntax, ConstructorDeclarationStructureProvider>();
builder.Add<ConversionOperatorDeclarationSyntax, ConversionOperatorDeclarationStructureProvider>();
builder.Add<DelegateDeclarationSyntax, DelegateDeclarationStructureProvider>();
builder.Add<DestructorDeclarationSyntax, DestructorDeclarationStructureProvider>();
builder.Add<DocumentationCommentTriviaSyntax, DocumentationCommentStructureProvider>();
builder.Add<EnumDeclarationSyntax, EnumDeclarationStructureProvider>();
builder.Add<EnumMemberDeclarationSyntax, EnumMemberDeclarationStructureProvider>();
builder.Add<EventDeclarationSyntax, EventDeclarationStructureProvider>();
builder.Add<EventFieldDeclarationSyntax, EventFieldDeclarationStructureProvider>();
builder.Add<FieldDeclarationSyntax, FieldDeclarationStructureProvider>();
builder.Add<IndexerDeclarationSyntax, IndexerDeclarationStructureProvider>();
builder.Add<InitializerExpressionSyntax, InitializerExpressionStructureProvider>();
builder.Add<InterfaceDeclarationSyntax, TypeDeclarationStructureProvider>();
builder.Add<MethodDeclarationSyntax, MethodDeclarationStructureProvider>();
builder.Add<NamespaceDeclarationSyntax, NamespaceDeclarationStructureProvider>();
builder.Add<OperatorDeclarationSyntax, OperatorDeclarationStructureProvider>();
builder.Add<ParenthesizedLambdaExpressionSyntax, ParenthesizedLambdaExpressionStructureProvider>();
builder.Add<PropertyDeclarationSyntax, PropertyDeclarationStructureProvider>();
builder.Add<RecordDeclarationSyntax, TypeDeclarationStructureProvider>();
builder.Add<RegionDirectiveTriviaSyntax, RegionDirectiveStructureProvider>();
builder.Add<SimpleLambdaExpressionSyntax, SimpleLambdaExpressionStructureProvider>();
builder.Add<StructDeclarationSyntax, TypeDeclarationStructureProvider>();
builder.Add<SwitchStatementSyntax, SwitchStatementStructureProvider>();
builder.Add<LiteralExpressionSyntax, StringLiteralExpressionStructureProvider>();
builder.Add<InterpolatedStringExpressionSyntax, InterpolatedStringExpressionStructureProvider>();
return builder.ToImmutable();
}
private static ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> CreateDefaultTriviaProviderMap()
{
var builder = ImmutableDictionary.CreateBuilder<int, ImmutableArray<AbstractSyntaxStructureProvider>>();
builder.Add((int)SyntaxKind.DisabledTextTrivia, ImmutableArray.Create<AbstractSyntaxStructureProvider>(new DisabledTextTriviaStructureProvider()));
return builder.ToImmutable();
}
internal CSharpBlockStructureProvider()
: base(CreateDefaultNodeProviderMap(), CreateDefaultTriviaProviderMap())
{
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractObjectBrowserLibraryManager_Search.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
{
internal abstract partial class AbstractObjectBrowserLibraryManager
{
private static string GetSearchText(VSOBSEARCHCRITERIA2[] pobSrch)
{
if (pobSrch.Length == 0 ||
pobSrch[0].szName == null)
{
return null;
}
var searchText = pobSrch[0].szName;
var openParenIndex = searchText.IndexOf('(');
if (openParenIndex != -1)
{
searchText = searchText.Substring(openParenIndex);
}
return searchText;
}
public IVsSimpleObjectList2 GetSearchList(
ObjectListKind listKind,
uint flags,
VSOBSEARCHCRITERIA2[] pobSrch,
ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> projectAndAssemblySet)
{
var searchText = GetSearchText(pobSrch);
if (searchText == null)
{
return null;
}
// TODO: Support wildcards (e.g. *xyz, *xyz* and xyz*) like the old language service did.
switch (listKind)
{
case ObjectListKind.Namespaces:
{
var builder = ImmutableArray.CreateBuilder<ObjectListItem>();
foreach (var projectIdAndAssembly in projectAndAssemblySet)
{
var projectId = projectIdAndAssembly.Item1;
var assemblySymbol = projectIdAndAssembly.Item2;
CollectNamespaceListItems(assemblySymbol, projectId, builder, searchText);
}
return new ObjectList(ObjectListKind.Namespaces, flags, this, builder.ToImmutable());
}
case ObjectListKind.Types:
{
var builder = ImmutableArray.CreateBuilder<ObjectListItem>();
foreach (var projectIdAndAssembly in projectAndAssemblySet)
{
var projectId = projectIdAndAssembly.Item1;
var assemblySymbol = projectIdAndAssembly.Item2;
var compilation = this.GetCompilation(projectId);
if (compilation == null)
{
return null;
}
CollectTypeListItems(assemblySymbol, compilation, projectId, builder, searchText);
}
return new ObjectList(ObjectListKind.Types, flags, this, builder.ToImmutable());
}
case ObjectListKind.Members:
{
var builder = ImmutableArray.CreateBuilder<ObjectListItem>();
foreach (var projectIdAndAssembly in projectAndAssemblySet)
{
var projectId = projectIdAndAssembly.Item1;
var assemblySymbol = projectIdAndAssembly.Item2;
var compilation = this.GetCompilation(projectId);
if (compilation == null)
{
return null;
}
CollectMemberListItems(assemblySymbol, compilation, projectId, builder, searchText);
}
return new ObjectList(ObjectListKind.Types, flags, this, builder.ToImmutable());
}
default:
return null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
{
internal abstract partial class AbstractObjectBrowserLibraryManager
{
private static string GetSearchText(VSOBSEARCHCRITERIA2[] pobSrch)
{
if (pobSrch.Length == 0 ||
pobSrch[0].szName == null)
{
return null;
}
var searchText = pobSrch[0].szName;
var openParenIndex = searchText.IndexOf('(');
if (openParenIndex != -1)
{
searchText = searchText.Substring(openParenIndex);
}
return searchText;
}
public IVsSimpleObjectList2 GetSearchList(
ObjectListKind listKind,
uint flags,
VSOBSEARCHCRITERIA2[] pobSrch,
ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> projectAndAssemblySet)
{
var searchText = GetSearchText(pobSrch);
if (searchText == null)
{
return null;
}
// TODO: Support wildcards (e.g. *xyz, *xyz* and xyz*) like the old language service did.
switch (listKind)
{
case ObjectListKind.Namespaces:
{
var builder = ImmutableArray.CreateBuilder<ObjectListItem>();
foreach (var projectIdAndAssembly in projectAndAssemblySet)
{
var projectId = projectIdAndAssembly.Item1;
var assemblySymbol = projectIdAndAssembly.Item2;
CollectNamespaceListItems(assemblySymbol, projectId, builder, searchText);
}
return new ObjectList(ObjectListKind.Namespaces, flags, this, builder.ToImmutable());
}
case ObjectListKind.Types:
{
var builder = ImmutableArray.CreateBuilder<ObjectListItem>();
foreach (var projectIdAndAssembly in projectAndAssemblySet)
{
var projectId = projectIdAndAssembly.Item1;
var assemblySymbol = projectIdAndAssembly.Item2;
var compilation = this.GetCompilation(projectId);
if (compilation == null)
{
return null;
}
CollectTypeListItems(assemblySymbol, compilation, projectId, builder, searchText);
}
return new ObjectList(ObjectListKind.Types, flags, this, builder.ToImmutable());
}
case ObjectListKind.Members:
{
var builder = ImmutableArray.CreateBuilder<ObjectListItem>();
foreach (var projectIdAndAssembly in projectAndAssemblySet)
{
var projectId = projectIdAndAssembly.Item1;
var assemblySymbol = projectIdAndAssembly.Item2;
var compilation = this.GetCompilation(projectId);
if (compilation == null)
{
return null;
}
CollectMemberListItems(assemblySymbol, compilation, projectId, builder, searchText);
}
return new ObjectList(ObjectListKind.Types, flags, this, builder.ToImmutable());
}
default:
return null;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenOverridingAndHiding.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenOverridingAndHiding
Inherits BasicTestBase
<WorkItem(540852, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540852")>
<Fact>
Public Sub TestSimpleMustOverride()
Dim source =
<compilation>
<file name="a.vb">
Imports System
MustInherit Class A
Public MustOverride Function F As Integer()
Protected MustOverride Sub Meth()
Protected Friend MustOverride Property Prop As Integer()
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32[] F() cil managed"),
Signature("A", "Meth", ".method family newslot strict abstract virtual instance System.Void Meth() cil managed"),
Signature("A", "get_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Int32[] get_Prop() cil managed"),
Signature("A", "set_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32[] Value) cil managed"),
Signature("A", "Prop", ".property readwrite System.Int32[] Prop")
})
End Sub
<WorkItem(528311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528311")>
<WorkItem(540865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540865")>
<Fact>
Public Sub TestSimpleOverrides()
Dim source =
<compilation>
<file name="a.vb">
MustInherit Class A
Public MustOverride Sub F()
End Class
Class B
Inherits A
Public Overrides Sub F()
End Sub
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "F", ".method public hidebysig strict virtual instance System.Void F() cil managed"),
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Void F() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(540884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540884")>
<Fact>
Public Sub TestMustOverrideOverrides()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub G()
Console.WriteLine("A.G")
End Sub
End Class
MustInherit Class B
Inherits A
Public MustOverride Overrides Sub G()
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "G", ".method public hidebysig strict abstract virtual instance System.Void G() cil managed"),
Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(542576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542576")>
<Fact>
Public Sub TestDontMergePartials()
Dim source =
<compilation>
<file name="a.vb">
MustInherit Class A
MustOverride Function F() As Integer
Overridable Sub G()
End Sub
End Class
Partial Class B
Inherits A
'This would normally be an error if this partial part for class B
'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable
'can't be combined). Strangely Dev10 doesn't report the same error
'when the NotInheritable modifier appears on a different partial part.
NotOverridable Overrides Function F() As Integer
Return 1
End Function
'This would normally be an error if this partial part for class B
'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable
'can't be combined). Strangely Dev10 doesn't report the same error
'when the NotInheritable modifier appears on a different partial part.
NotOverridable Overrides Sub G()
End Sub
End Class</file>
<file name="b.vb">
NotInheritable Class B
Inherits A
End Class
</file>
</compilation>
CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "F", ".method public hidebysig strict virtual final instance System.Int32 F() cil managed"),
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32 F() cil managed"),
Signature("B", "G", ".method public hidebysig strict virtual final instance System.Void G() cil managed"),
Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed")
}).
VerifyDiagnostics()
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact(), WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
Public Sub TestMustOverloadWithOptional()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Program
Const str As String = ""
Sub Main(args As String())
End Sub
Function fun()
test(temp:=Nothing, x:=1)
Return Nothing
End Function
Function test(ByRef x As Integer, temp As Object, Optional y As String = str, Optional z As Object = Nothing)
Return Nothing
End Function
Function test(ByRef x As Integer, Optional temp As Object = Nothing)
Return Nothing
End Function
End Module
</file>
</compilation>).
VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase1()
'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this
'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[using System;
public abstract class C2 : C1
{
new internal virtual void goo()
{
Console.WriteLine("C2");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Imports System
Public Class C3 : Inherits C2
Public Overrides Sub goo
Console.WriteLine("C3")
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors.
'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
'C1 : Public MustOverride Sub goo().
'Public Class C4 : Inherits C3
' ~~
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[
Imports System
Public Class C4 : Inherits C3
End Class
Public Class C5 : Inherits C2
' Corresponding case in C# results in PEVerify errors - See test 'CrossLanguageCase1' in CodeGenOverridingAndHiding.cs
Public Overrides Sub goo()
Console.WriteLine("C5")
End Sub
End Class
Public Module Program
Sub Main()
Dim x As C1 = New C4
x.goo()
Dim y As C2 = New C5
y.Goo()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
Dim vb3Verifier = CompileAndVerify(vb3Compilation,
expectedOutput:=<![CDATA[C3
C5]]>)
vb3Verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase2()
'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this
'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[using System;
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
Console.WriteLine("C2");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Imports System
Public Class C3 : Inherits C2
Public Overrides Sub goo
Console.WriteLine("C3")
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors.
'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
'C1 : Public MustOverride Sub goo().
'Public Class C4 : Inherits C3
' ~~
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[Imports System
Public Class C4 : Inherits C3
Public Overrides Sub goo
Console.WriteLine("C4")
End Sub
End Class
Public Module Program
Sub Main()
Dim x As C1 = New C4
x.goo
Dim y As C2 = New C4
y.goo
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
Dim vb3Verifier = CompileAndVerify(vb3Compilation,
expectedOutput:=<![CDATA[C4
C2]]>)
vb3Verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase3()
'Note: Dev10 and Roslyn produce identical errors for this case.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Public Class C3 : Inherits C2
Public Overrides Sub goo
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[MustInherit Public Class C4 : Inherits C3
Public Overrides Sub goo
End Sub
End Class
Public Class C5 : Inherits C2
Public Overrides Sub goo()
End Sub
End Class
Public Class C6 : Inherits C2
Friend Overrides Sub goo()
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
vb3Compilation.AssertTheseDiagnostics(<expected>
BC30610: Class 'C5' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
C1: Public MustOverride Sub goo().
Public Class C5 : Inherits C2
~~
BC30266: 'Public Overrides Sub goo()' cannot override 'Friend Overridable Overloads Sub goo()' because they have different access levels.
Public Overrides Sub goo()
~~~
BC30610: Class 'C6' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
C1: Public MustOverride Sub goo().
Public Class C6 : Inherits C2
~~
</expected>)
End Sub
<WorkItem(543794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543794")>
<Fact()>
Public Sub CrossLanguageTest4()
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VB2")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[MustInherit Public Class C3 : Inherits C2
Friend Overrides Sub goo()
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
CompileAndVerify(vb2Compilation).VerifyDiagnostics()
End Sub
<Fact(), WorkItem(544536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544536")>
Public Sub VBOverrideCsharpOptional()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[
public abstract class Trivia
{
public abstract void Format(int i, int j = 2);
}
public class Whitespace : Trivia
{
public override void Format(int i, int j) {}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[
MustInherit Class AbstractLineBreakTrivia
Inherits Whitespace
Public Overrides Sub Format(i As Integer, j As Integer)
End Sub
End Class
Class AfterStatementTerminatorTokenTrivia
Inherits AbstractLineBreakTrivia
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={cs1Compilation})
CompileAndVerify(vb2Compilation).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub VBOverrideCsharpOptional2()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[
public abstract class Trivia
{
public abstract void Format(int i, int j = 2);
}
public class Whitespace : Trivia
{
public override void Format(int i, int j) {}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[
MustInherit Class AbstractLineBreakTrivia
Inherits Trivia
Public Overrides Sub Format(i As Integer, j As Integer)
End Sub
End Class
Class AfterStatementTerminatorTokenTrivia
Inherits AbstractLineBreakTrivia
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={cs1Compilation})
CompilationUtils.AssertTheseDiagnostics(vb2Compilation, <expected>
BC30308: 'Public Overrides Sub Format(i As Integer, j As Integer)' cannot override 'Public MustOverride Overloads Sub Format(i As Integer, [j As Integer = 2])' because they differ by optional parameters.
Public Overrides Sub Format(i As Integer, j As Integer)
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub OverloadingBasedOnOptionalParameters()
' NOTE: this matches Dev11 implementation, not Dev10
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C ' allowed
Shared Sub f(ByVal x As Integer)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 0)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal s As String = "")
End Sub
End Class
Class C2 ' allowed
Shared Sub f(ByVal x As Integer, Optional ByVal y As Short = 1)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 1)
End Sub
End Class
Class C3 ' allowed
Shared Sub f()
End Sub
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
End Class
Class C4 ' allowed`
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByVal ParamArray xx As Integer())
End Sub
End Class
Class C5 ' disallowed
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByVal x As Integer)
End Sub
End Class
Class C6 ' disallowed
Shared Sub f(Optional ByVal x As Integer() = Nothing)
End Sub
Shared Sub f(ByVal ParamArray xx As Integer())
End Sub
End Class
Class C7 ' disallowed
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByRef x As Integer)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(x As Integer)' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer = 0)
~
BC30300: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer() = Nothing)
~
BC30368: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Shared Sub f(Optional ByVal x As Integer() = Nothing)
~
BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer = 0)
~
BC30345: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Shared Sub f(Optional ByVal x As Integer = 0)
~
</errors>)
End Sub
<Fact()>
Public Sub HidingBySignatureWithOptionalParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
Console.WriteLine("A::f(Optional x As String = """")")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
Console.WriteLine("B::f()")
End Sub
End Class
Class C
Inherits B
Public Sub f(Optional x As String = "")
Console.WriteLine("C::f(Optional x As String = """")")
End Sub
Public Shared Sub Main()
Dim c As B = New C
c.f()
c.f(1)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC40005: sub 'f' shadows an overridable method in the base class 'B'. To override the base method, this method must be declared 'Overrides'.
Public Sub f(Optional x As String = "")
~
</errors>)
End Sub
<Fact()>
Public Sub BC31404ForOverloadingBasedOnOptionalParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
MustInherit Class A
Public MustOverride Sub f(Optional x As String = "")
End Class
MustInherit Class B1
Inherits A
Public MustOverride Overloads Sub f(Optional x As String = "")
End Class
MustInherit Class B2
Inherits A
Public MustOverride Overloads Sub f(x As String)
End Class
MustInherit Class B3
Inherits A
Public MustOverride Overloads Sub f(x As Integer, Optional y As String = "")
End Class
MustInherit Class B4
Inherits A
Public MustOverride Overloads Sub f()
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC31404: 'Public MustOverride Overloads Sub f([x As String = ""])' cannot shadow a method declared 'MustOverride'.
Public MustOverride Overloads Sub f(Optional x As String = "")
~
BC31404: 'Public MustOverride Overloads Sub f(x As String)' cannot shadow a method declared 'MustOverride'.
Public MustOverride Overloads Sub f(x As String)
~
</errors>)
End Sub
<Fact()>
Public Sub OverloadingWithNotAccessibleMethods()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
End Sub
End Class
Class BB
Inherits A
Private Overloads Sub f()
End Sub
Private Overloads Sub f(Optional x As String = "")
End Sub
End Class
Class C
Inherits BB
Public Overloads Overrides Sub f(Optional x As String = "")
Console.Write("f(Optional x As String = "");")
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
</errors>)
End Sub
<Fact()>
Public Sub AddressOfWithFunctionOrSub1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Clazz
Public Shared Sub S(Optional x As Integer = 0)
Console.WriteLine("Sub S")
End Sub
Public Shared Function S() As Boolean
Console.WriteLine("Function S")
Return True
End Function
Public Shared Sub Main()
Dim a As action = AddressOf S
a()
End Sub
End Class
</file>
</compilation>, expectedOutput:="Function S")
End Sub
<Fact, WorkItem(546816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546816")>
Public Sub OverrideFinalizeWithoutNewslot()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class SelfDestruct
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
</file>
</compilation>,
{MscorlibRef_v20}).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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenOverridingAndHiding
Inherits BasicTestBase
<WorkItem(540852, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540852")>
<Fact>
Public Sub TestSimpleMustOverride()
Dim source =
<compilation>
<file name="a.vb">
Imports System
MustInherit Class A
Public MustOverride Function F As Integer()
Protected MustOverride Sub Meth()
Protected Friend MustOverride Property Prop As Integer()
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32[] F() cil managed"),
Signature("A", "Meth", ".method family newslot strict abstract virtual instance System.Void Meth() cil managed"),
Signature("A", "get_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Int32[] get_Prop() cil managed"),
Signature("A", "set_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32[] Value) cil managed"),
Signature("A", "Prop", ".property readwrite System.Int32[] Prop")
})
End Sub
<WorkItem(528311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528311")>
<WorkItem(540865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540865")>
<Fact>
Public Sub TestSimpleOverrides()
Dim source =
<compilation>
<file name="a.vb">
MustInherit Class A
Public MustOverride Sub F()
End Class
Class B
Inherits A
Public Overrides Sub F()
End Sub
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "F", ".method public hidebysig strict virtual instance System.Void F() cil managed"),
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Void F() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(540884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540884")>
<Fact>
Public Sub TestMustOverrideOverrides()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub G()
Console.WriteLine("A.G")
End Sub
End Class
MustInherit Class B
Inherits A
Public MustOverride Overrides Sub G()
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "G", ".method public hidebysig strict abstract virtual instance System.Void G() cil managed"),
Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(542576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542576")>
<Fact>
Public Sub TestDontMergePartials()
Dim source =
<compilation>
<file name="a.vb">
MustInherit Class A
MustOverride Function F() As Integer
Overridable Sub G()
End Sub
End Class
Partial Class B
Inherits A
'This would normally be an error if this partial part for class B
'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable
'can't be combined). Strangely Dev10 doesn't report the same error
'when the NotInheritable modifier appears on a different partial part.
NotOverridable Overrides Function F() As Integer
Return 1
End Function
'This would normally be an error if this partial part for class B
'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable
'can't be combined). Strangely Dev10 doesn't report the same error
'when the NotInheritable modifier appears on a different partial part.
NotOverridable Overrides Sub G()
End Sub
End Class</file>
<file name="b.vb">
NotInheritable Class B
Inherits A
End Class
</file>
</compilation>
CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "F", ".method public hidebysig strict virtual final instance System.Int32 F() cil managed"),
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32 F() cil managed"),
Signature("B", "G", ".method public hidebysig strict virtual final instance System.Void G() cil managed"),
Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed")
}).
VerifyDiagnostics()
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact(), WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
Public Sub TestMustOverloadWithOptional()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Program
Const str As String = ""
Sub Main(args As String())
End Sub
Function fun()
test(temp:=Nothing, x:=1)
Return Nothing
End Function
Function test(ByRef x As Integer, temp As Object, Optional y As String = str, Optional z As Object = Nothing)
Return Nothing
End Function
Function test(ByRef x As Integer, Optional temp As Object = Nothing)
Return Nothing
End Function
End Module
</file>
</compilation>).
VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase1()
'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this
'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[using System;
public abstract class C2 : C1
{
new internal virtual void goo()
{
Console.WriteLine("C2");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Imports System
Public Class C3 : Inherits C2
Public Overrides Sub goo
Console.WriteLine("C3")
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors.
'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
'C1 : Public MustOverride Sub goo().
'Public Class C4 : Inherits C3
' ~~
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[
Imports System
Public Class C4 : Inherits C3
End Class
Public Class C5 : Inherits C2
' Corresponding case in C# results in PEVerify errors - See test 'CrossLanguageCase1' in CodeGenOverridingAndHiding.cs
Public Overrides Sub goo()
Console.WriteLine("C5")
End Sub
End Class
Public Module Program
Sub Main()
Dim x As C1 = New C4
x.goo()
Dim y As C2 = New C5
y.Goo()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
Dim vb3Verifier = CompileAndVerify(vb3Compilation,
expectedOutput:=<![CDATA[C3
C5]]>)
vb3Verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase2()
'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this
'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[using System;
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
Console.WriteLine("C2");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Imports System
Public Class C3 : Inherits C2
Public Overrides Sub goo
Console.WriteLine("C3")
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors.
'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
'C1 : Public MustOverride Sub goo().
'Public Class C4 : Inherits C3
' ~~
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[Imports System
Public Class C4 : Inherits C3
Public Overrides Sub goo
Console.WriteLine("C4")
End Sub
End Class
Public Module Program
Sub Main()
Dim x As C1 = New C4
x.goo
Dim y As C2 = New C4
y.goo
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
Dim vb3Verifier = CompileAndVerify(vb3Compilation,
expectedOutput:=<![CDATA[C4
C2]]>)
vb3Verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase3()
'Note: Dev10 and Roslyn produce identical errors for this case.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Public Class C3 : Inherits C2
Public Overrides Sub goo
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[MustInherit Public Class C4 : Inherits C3
Public Overrides Sub goo
End Sub
End Class
Public Class C5 : Inherits C2
Public Overrides Sub goo()
End Sub
End Class
Public Class C6 : Inherits C2
Friend Overrides Sub goo()
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
vb3Compilation.AssertTheseDiagnostics(<expected>
BC30610: Class 'C5' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
C1: Public MustOverride Sub goo().
Public Class C5 : Inherits C2
~~
BC30266: 'Public Overrides Sub goo()' cannot override 'Friend Overridable Overloads Sub goo()' because they have different access levels.
Public Overrides Sub goo()
~~~
BC30610: Class 'C6' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
C1: Public MustOverride Sub goo().
Public Class C6 : Inherits C2
~~
</expected>)
End Sub
<WorkItem(543794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543794")>
<Fact()>
Public Sub CrossLanguageTest4()
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VB2")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[MustInherit Public Class C3 : Inherits C2
Friend Overrides Sub goo()
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
CompileAndVerify(vb2Compilation).VerifyDiagnostics()
End Sub
<Fact(), WorkItem(544536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544536")>
Public Sub VBOverrideCsharpOptional()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[
public abstract class Trivia
{
public abstract void Format(int i, int j = 2);
}
public class Whitespace : Trivia
{
public override void Format(int i, int j) {}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[
MustInherit Class AbstractLineBreakTrivia
Inherits Whitespace
Public Overrides Sub Format(i As Integer, j As Integer)
End Sub
End Class
Class AfterStatementTerminatorTokenTrivia
Inherits AbstractLineBreakTrivia
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={cs1Compilation})
CompileAndVerify(vb2Compilation).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub VBOverrideCsharpOptional2()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[
public abstract class Trivia
{
public abstract void Format(int i, int j = 2);
}
public class Whitespace : Trivia
{
public override void Format(int i, int j) {}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[
MustInherit Class AbstractLineBreakTrivia
Inherits Trivia
Public Overrides Sub Format(i As Integer, j As Integer)
End Sub
End Class
Class AfterStatementTerminatorTokenTrivia
Inherits AbstractLineBreakTrivia
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={cs1Compilation})
CompilationUtils.AssertTheseDiagnostics(vb2Compilation, <expected>
BC30308: 'Public Overrides Sub Format(i As Integer, j As Integer)' cannot override 'Public MustOverride Overloads Sub Format(i As Integer, [j As Integer = 2])' because they differ by optional parameters.
Public Overrides Sub Format(i As Integer, j As Integer)
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub OverloadingBasedOnOptionalParameters()
' NOTE: this matches Dev11 implementation, not Dev10
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C ' allowed
Shared Sub f(ByVal x As Integer)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 0)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal s As String = "")
End Sub
End Class
Class C2 ' allowed
Shared Sub f(ByVal x As Integer, Optional ByVal y As Short = 1)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 1)
End Sub
End Class
Class C3 ' allowed
Shared Sub f()
End Sub
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
End Class
Class C4 ' allowed`
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByVal ParamArray xx As Integer())
End Sub
End Class
Class C5 ' disallowed
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByVal x As Integer)
End Sub
End Class
Class C6 ' disallowed
Shared Sub f(Optional ByVal x As Integer() = Nothing)
End Sub
Shared Sub f(ByVal ParamArray xx As Integer())
End Sub
End Class
Class C7 ' disallowed
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByRef x As Integer)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(x As Integer)' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer = 0)
~
BC30300: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer() = Nothing)
~
BC30368: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Shared Sub f(Optional ByVal x As Integer() = Nothing)
~
BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer = 0)
~
BC30345: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Shared Sub f(Optional ByVal x As Integer = 0)
~
</errors>)
End Sub
<Fact()>
Public Sub HidingBySignatureWithOptionalParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
Console.WriteLine("A::f(Optional x As String = """")")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
Console.WriteLine("B::f()")
End Sub
End Class
Class C
Inherits B
Public Sub f(Optional x As String = "")
Console.WriteLine("C::f(Optional x As String = """")")
End Sub
Public Shared Sub Main()
Dim c As B = New C
c.f()
c.f(1)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC40005: sub 'f' shadows an overridable method in the base class 'B'. To override the base method, this method must be declared 'Overrides'.
Public Sub f(Optional x As String = "")
~
</errors>)
End Sub
<Fact()>
Public Sub BC31404ForOverloadingBasedOnOptionalParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
MustInherit Class A
Public MustOverride Sub f(Optional x As String = "")
End Class
MustInherit Class B1
Inherits A
Public MustOverride Overloads Sub f(Optional x As String = "")
End Class
MustInherit Class B2
Inherits A
Public MustOverride Overloads Sub f(x As String)
End Class
MustInherit Class B3
Inherits A
Public MustOverride Overloads Sub f(x As Integer, Optional y As String = "")
End Class
MustInherit Class B4
Inherits A
Public MustOverride Overloads Sub f()
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC31404: 'Public MustOverride Overloads Sub f([x As String = ""])' cannot shadow a method declared 'MustOverride'.
Public MustOverride Overloads Sub f(Optional x As String = "")
~
BC31404: 'Public MustOverride Overloads Sub f(x As String)' cannot shadow a method declared 'MustOverride'.
Public MustOverride Overloads Sub f(x As String)
~
</errors>)
End Sub
<Fact()>
Public Sub OverloadingWithNotAccessibleMethods()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
End Sub
End Class
Class BB
Inherits A
Private Overloads Sub f()
End Sub
Private Overloads Sub f(Optional x As String = "")
End Sub
End Class
Class C
Inherits BB
Public Overloads Overrides Sub f(Optional x As String = "")
Console.Write("f(Optional x As String = "");")
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
</errors>)
End Sub
<Fact()>
Public Sub AddressOfWithFunctionOrSub1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Clazz
Public Shared Sub S(Optional x As Integer = 0)
Console.WriteLine("Sub S")
End Sub
Public Shared Function S() As Boolean
Console.WriteLine("Function S")
Return True
End Function
Public Shared Sub Main()
Dim a As action = AddressOf S
a()
End Sub
End Class
</file>
</compilation>, expectedOutput:="Function S")
End Sub
<Fact, WorkItem(546816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546816")>
Public Sub OverrideFinalizeWithoutNewslot()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class SelfDestruct
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
</file>
</compilation>,
{MscorlibRef_v20}).VerifyDiagnostics()
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/VisualStudio/Core/Impl/CodeModel/Collections/NamespaceCollection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICodeElements))]
public sealed class NamespaceCollection : AbstractCodeElementCollection
{
internal static EnvDTE.CodeElements Create(
CodeModelState state,
object parent,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey)
{
var collection = new NamespaceCollection(state, parent, fileCodeModel, nodeKey);
return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
}
private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel;
private readonly SyntaxNodeKey _nodeKey;
private NamespaceCollection(
CodeModelState state,
object parent,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey)
: base(state, parent)
{
Debug.Assert(fileCodeModel != null);
_fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel);
_nodeKey = nodeKey;
}
private FileCodeModel FileCodeModel
{
get { return _fileCodeModel.Object; }
}
private bool IsRootNamespace
{
get { return _nodeKey == SyntaxNodeKey.Empty; }
}
private SyntaxNode LookupNode()
{
if (!IsRootNamespace)
{
return FileCodeModel.LookupNode(_nodeKey);
}
else
{
return FileCodeModel.GetSyntaxRoot();
}
}
private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node, SyntaxNode parentNode)
{
CodeModelService.GetOptionNameAndOrdinal(parentNode, node, out var name, out var ordinal);
return CodeOptionsStatement.Create(this.State, this.FileCodeModel, name, ordinal);
}
private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node, AbstractCodeElement parentElement)
{
var name = CodeModelService.GetImportNamespaceOrType(node);
return CodeImport.Create(this.State, this.FileCodeModel, parentElement, name);
}
private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node, SyntaxNode parentNode, AbstractCodeElement parentElement)
{
CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal);
return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this.FileCodeModel, parentElement, name, ordinal);
}
internal override Snapshot CreateSnapshot()
{
var node = LookupNode();
var parentElement = !this.IsRootNamespace
? (AbstractCodeElement)this.Parent
: null;
var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance();
nodesBuilder.AddRange(CodeModelService.GetOptionNodes(node));
nodesBuilder.AddRange(CodeModelService.GetImportNodes(node));
nodesBuilder.AddRange(CodeModelService.GetAttributeNodes(node));
nodesBuilder.AddRange(CodeModelService.GetLogicalSupportedMemberNodes(node));
return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement,
nodesBuilder.ToImmutableAndFree());
}
protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element)
{
var node = LookupNode();
var parentElement = !this.IsRootNamespace
? (AbstractCodeElement)this.Parent
: null;
var currentIndex = 0;
// Option statements
var optionNodes = CodeModelService.GetOptionNodes(node);
var optionNodeCount = optionNodes.Count();
if (index < currentIndex + optionNodeCount)
{
var child = optionNodes.ElementAt(index - currentIndex);
element = CreateCodeOptionsStatement(child, node);
return true;
}
currentIndex += optionNodeCount;
// Imports/using statements
var importNodes = CodeModelService.GetImportNodes(node);
var importNodeCount = importNodes.Count();
if (index < currentIndex + importNodeCount)
{
var child = importNodes.ElementAt(index - currentIndex);
element = CreateCodeImport(child, parentElement);
return true;
}
currentIndex += importNodeCount;
// Attributes
var attributeNodes = CodeModelService.GetAttributeNodes(node);
var attributeNodeCount = attributeNodes.Count();
if (index < currentIndex + attributeNodeCount)
{
var child = attributeNodes.ElementAt(index - currentIndex);
element = CreateCodeAttribute(child, node, parentElement);
return true;
}
currentIndex += attributeNodeCount;
// Members
var memberNodes = CodeModelService.GetLogicalSupportedMemberNodes(node);
var memberNodeCount = memberNodes.Count();
if (index < currentIndex + memberNodeCount)
{
var child = memberNodes.ElementAt(index - currentIndex);
element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child);
return true;
}
element = null;
return false;
}
protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
{
var node = LookupNode();
var parentElement = !IsRootNamespace
? (AbstractCodeElement)Parent
: null;
// Option statements
foreach (var child in CodeModelService.GetOptionNodes(node))
{
CodeModelService.GetOptionNameAndOrdinal(node, child, out var childName, out var ordinal);
if (childName == name)
{
element = CodeOptionsStatement.Create(State, FileCodeModel, childName, ordinal);
return true;
}
}
// Imports/using statements
foreach (var child in CodeModelService.GetImportNodes(node))
{
var childName = CodeModelService.GetImportNamespaceOrType(child);
if (childName == name)
{
element = CodeImport.Create(State, FileCodeModel, parentElement, childName);
return true;
}
}
// Attributes
foreach (var child in CodeModelService.GetAttributeNodes(node))
{
CodeModelService.GetAttributeNameAndOrdinal(node, child, out var childName, out var ordinal);
if (childName == name)
{
element = (EnvDTE.CodeElement)CodeAttribute.Create(State, FileCodeModel, parentElement, childName, ordinal);
return true;
}
}
// Members
foreach (var child in CodeModelService.GetLogicalSupportedMemberNodes(node))
{
var childName = CodeModelService.GetName(child);
if (childName == name)
{
element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child);
return true;
}
}
element = null;
return false;
}
public override int Count
{
get
{
var node = LookupNode();
return
CodeModelService.GetOptionNodes(node).Count() +
CodeModelService.GetImportNodes(node).Count() +
CodeModelService.GetAttributeNodes(node).Count() +
CodeModelService.GetLogicalSupportedMemberNodes(node).Count();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICodeElements))]
public sealed class NamespaceCollection : AbstractCodeElementCollection
{
internal static EnvDTE.CodeElements Create(
CodeModelState state,
object parent,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey)
{
var collection = new NamespaceCollection(state, parent, fileCodeModel, nodeKey);
return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
}
private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel;
private readonly SyntaxNodeKey _nodeKey;
private NamespaceCollection(
CodeModelState state,
object parent,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey)
: base(state, parent)
{
Debug.Assert(fileCodeModel != null);
_fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel);
_nodeKey = nodeKey;
}
private FileCodeModel FileCodeModel
{
get { return _fileCodeModel.Object; }
}
private bool IsRootNamespace
{
get { return _nodeKey == SyntaxNodeKey.Empty; }
}
private SyntaxNode LookupNode()
{
if (!IsRootNamespace)
{
return FileCodeModel.LookupNode(_nodeKey);
}
else
{
return FileCodeModel.GetSyntaxRoot();
}
}
private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node, SyntaxNode parentNode)
{
CodeModelService.GetOptionNameAndOrdinal(parentNode, node, out var name, out var ordinal);
return CodeOptionsStatement.Create(this.State, this.FileCodeModel, name, ordinal);
}
private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node, AbstractCodeElement parentElement)
{
var name = CodeModelService.GetImportNamespaceOrType(node);
return CodeImport.Create(this.State, this.FileCodeModel, parentElement, name);
}
private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node, SyntaxNode parentNode, AbstractCodeElement parentElement)
{
CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal);
return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this.FileCodeModel, parentElement, name, ordinal);
}
internal override Snapshot CreateSnapshot()
{
var node = LookupNode();
var parentElement = !this.IsRootNamespace
? (AbstractCodeElement)this.Parent
: null;
var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance();
nodesBuilder.AddRange(CodeModelService.GetOptionNodes(node));
nodesBuilder.AddRange(CodeModelService.GetImportNodes(node));
nodesBuilder.AddRange(CodeModelService.GetAttributeNodes(node));
nodesBuilder.AddRange(CodeModelService.GetLogicalSupportedMemberNodes(node));
return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement,
nodesBuilder.ToImmutableAndFree());
}
protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element)
{
var node = LookupNode();
var parentElement = !this.IsRootNamespace
? (AbstractCodeElement)this.Parent
: null;
var currentIndex = 0;
// Option statements
var optionNodes = CodeModelService.GetOptionNodes(node);
var optionNodeCount = optionNodes.Count();
if (index < currentIndex + optionNodeCount)
{
var child = optionNodes.ElementAt(index - currentIndex);
element = CreateCodeOptionsStatement(child, node);
return true;
}
currentIndex += optionNodeCount;
// Imports/using statements
var importNodes = CodeModelService.GetImportNodes(node);
var importNodeCount = importNodes.Count();
if (index < currentIndex + importNodeCount)
{
var child = importNodes.ElementAt(index - currentIndex);
element = CreateCodeImport(child, parentElement);
return true;
}
currentIndex += importNodeCount;
// Attributes
var attributeNodes = CodeModelService.GetAttributeNodes(node);
var attributeNodeCount = attributeNodes.Count();
if (index < currentIndex + attributeNodeCount)
{
var child = attributeNodes.ElementAt(index - currentIndex);
element = CreateCodeAttribute(child, node, parentElement);
return true;
}
currentIndex += attributeNodeCount;
// Members
var memberNodes = CodeModelService.GetLogicalSupportedMemberNodes(node);
var memberNodeCount = memberNodes.Count();
if (index < currentIndex + memberNodeCount)
{
var child = memberNodes.ElementAt(index - currentIndex);
element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child);
return true;
}
element = null;
return false;
}
protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
{
var node = LookupNode();
var parentElement = !IsRootNamespace
? (AbstractCodeElement)Parent
: null;
// Option statements
foreach (var child in CodeModelService.GetOptionNodes(node))
{
CodeModelService.GetOptionNameAndOrdinal(node, child, out var childName, out var ordinal);
if (childName == name)
{
element = CodeOptionsStatement.Create(State, FileCodeModel, childName, ordinal);
return true;
}
}
// Imports/using statements
foreach (var child in CodeModelService.GetImportNodes(node))
{
var childName = CodeModelService.GetImportNamespaceOrType(child);
if (childName == name)
{
element = CodeImport.Create(State, FileCodeModel, parentElement, childName);
return true;
}
}
// Attributes
foreach (var child in CodeModelService.GetAttributeNodes(node))
{
CodeModelService.GetAttributeNameAndOrdinal(node, child, out var childName, out var ordinal);
if (childName == name)
{
element = (EnvDTE.CodeElement)CodeAttribute.Create(State, FileCodeModel, parentElement, childName, ordinal);
return true;
}
}
// Members
foreach (var child in CodeModelService.GetLogicalSupportedMemberNodes(node))
{
var childName = CodeModelService.GetName(child);
if (childName == name)
{
element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child);
return true;
}
}
element = null;
return false;
}
public override int Count
{
get
{
var node = LookupNode();
return
CodeModelService.GetOptionNodes(node).Count() +
CodeModelService.GetImportNodes(node).Count() +
CodeModelService.GetAttributeNodes(node).Count() +
CodeModelService.GetLogicalSupportedMemberNodes(node).Count();
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/Core/Portable/Workspace/Solution/VersionStamp.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// VersionStamp should be only used to compare versions returned by same API.
/// </summary>
public readonly struct VersionStamp : IEquatable<VersionStamp>, IObjectWritable
{
public static VersionStamp Default => default;
private const int GlobalVersionMarker = -1;
private const int InitialGlobalVersion = 10000;
/// <summary>
/// global counter to avoid collision within same session.
/// it starts with a big initial number just for a clarity in debugging
/// </summary>
private static int s_globalVersion = InitialGlobalVersion;
/// <summary>
/// time stamp
/// </summary>
private readonly DateTime _utcLastModified;
/// <summary>
/// indicate whether there was a collision on same item
/// </summary>
private readonly int _localIncrement;
/// <summary>
/// unique version in same session
/// </summary>
private readonly int _globalIncrement;
private VersionStamp(DateTime utcLastModified)
: this(utcLastModified, 0)
{
}
private VersionStamp(DateTime utcLastModified, int localIncrement)
: this(utcLastModified, localIncrement, GetNextGlobalVersion())
{
}
private VersionStamp(DateTime utcLastModified, int localIncrement, int globalIncrement)
{
if (utcLastModified != default && utcLastModified.Kind != DateTimeKind.Utc)
{
throw new ArgumentException(WorkspacesResources.DateTimeKind_must_be_Utc, nameof(utcLastModified));
}
_utcLastModified = utcLastModified;
_localIncrement = localIncrement;
_globalIncrement = globalIncrement;
}
/// <summary>
/// Creates a new instance of a VersionStamp.
/// </summary>
public static VersionStamp Create()
=> new(DateTime.UtcNow);
/// <summary>
/// Creates a new instance of a version stamp based on the specified DateTime.
/// </summary>
public static VersionStamp Create(DateTime utcTimeLastModified)
=> new(utcTimeLastModified);
/// <summary>
/// compare two different versions and return either one of the versions if there is no collision, otherwise, create a new version
/// that can be used later to compare versions between different items
/// </summary>
public VersionStamp GetNewerVersion(VersionStamp version)
{
// * NOTE *
// in current design/implementation, there are 4 possible ways for a version to be created.
//
// 1. created from a file stamp (most likely by starting a new session). "increment" will have 0 as value
// 2. created by modifying existing item (text changes, project changes etc).
// "increment" will have either 0 or previous increment + 1 if there was a collision.
// 3. created from deserialization (probably by using persistent service).
// 4. created by accumulating versions of multiple items.
//
// and this method is the one that is responsible for #4 case.
if (_utcLastModified > version._utcLastModified)
{
return this;
}
if (_utcLastModified == version._utcLastModified)
{
var thisGlobalVersion = GetGlobalVersion(this);
var thatGlobalVersion = GetGlobalVersion(version);
if (thisGlobalVersion == thatGlobalVersion)
{
// given versions are same one
return this;
}
// mark it as global version
// global version can't be moved to newer version.
return new VersionStamp(_utcLastModified, (thisGlobalVersion > thatGlobalVersion) ? thisGlobalVersion : thatGlobalVersion, GlobalVersionMarker);
}
return version;
}
/// <summary>
/// Gets a new VersionStamp that is guaranteed to be newer than its base one
/// this should only be used for same item to move it to newer version
/// </summary>
public VersionStamp GetNewerVersion()
{
// global version can't be moved to newer version
Debug.Assert(_globalIncrement != GlobalVersionMarker);
var now = DateTime.UtcNow;
var incr = (now == _utcLastModified) ? _localIncrement + 1 : 0;
return new VersionStamp(now, incr);
}
/// <summary>
/// Returns the serialized text form of the VersionStamp.
/// </summary>
public override string ToString()
{
// 'o' is the roundtrip format that captures the most detail.
return _utcLastModified.ToString("o") + "-" + _globalIncrement + "-" + _localIncrement;
}
public override int GetHashCode()
=> Hash.Combine(_utcLastModified.GetHashCode(), _localIncrement);
public override bool Equals(object? obj)
{
if (obj is VersionStamp v)
{
return this.Equals(v);
}
return false;
}
public bool Equals(VersionStamp version)
{
if (_utcLastModified == version._utcLastModified)
{
return GetGlobalVersion(this) == GetGlobalVersion(version);
}
return false;
}
public static bool operator ==(VersionStamp left, VersionStamp right)
=> left.Equals(right);
public static bool operator !=(VersionStamp left, VersionStamp right)
=> !left.Equals(right);
/// <summary>
/// Check whether given persisted version is re-usable. Used by VS for Mac
/// </summary>
internal static bool CanReusePersistedVersion(VersionStamp baseVersion, VersionStamp persistedVersion)
{
if (baseVersion == persistedVersion)
{
return true;
}
// there was a collision, we can't use these
if (baseVersion._localIncrement != 0 || persistedVersion._localIncrement != 0)
{
return false;
}
return baseVersion._utcLastModified == persistedVersion._utcLastModified;
}
bool IObjectWritable.ShouldReuseInSerialization => true;
void IObjectWritable.WriteTo(ObjectWriter writer)
=> WriteTo(writer);
internal void WriteTo(ObjectWriter writer)
{
writer.WriteInt64(_utcLastModified.ToBinary());
writer.WriteInt32(_localIncrement);
writer.WriteInt32(_globalIncrement);
}
internal static VersionStamp ReadFrom(ObjectReader reader)
{
var raw = reader.ReadInt64();
var localIncrement = reader.ReadInt32();
var globalIncrement = reader.ReadInt32();
return new VersionStamp(DateTime.FromBinary(raw), localIncrement, globalIncrement);
}
private static int GetGlobalVersion(VersionStamp version)
{
// global increment < 0 means it is a global version which has its global increment in local increment
return version._globalIncrement >= 0 ? version._globalIncrement : version._localIncrement;
}
private static int GetNextGlobalVersion()
{
// REVIEW: not sure what is best way to wrap it when it overflows. should I just throw or don't care.
// with 50ms (typing) as an interval for a new version, it gives more than 1 year before int32 to overflow.
// with 5ms as an interval, it gives more than 120 days before it overflows.
// since global version is only for per VS session, I think we don't need to worry about overflow.
// or we could use Int64 which will give more than a million years turn around even on 1ms interval.
// this will let versions to be compared safely between multiple items
// without worrying about collision within same session
var globalVersion = Interlocked.Increment(ref VersionStamp.s_globalVersion);
return globalVersion;
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly VersionStamp _versionStamp;
public TestAccessor(in VersionStamp versionStamp)
=> _versionStamp = versionStamp;
/// <summary>
/// True if this VersionStamp is newer than the specified one.
/// </summary>
internal bool IsNewerThan(in VersionStamp version)
{
if (_versionStamp._utcLastModified > version._utcLastModified)
{
return true;
}
if (_versionStamp._utcLastModified == version._utcLastModified)
{
return GetGlobalVersion(_versionStamp) > GetGlobalVersion(version);
}
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.Diagnostics;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// VersionStamp should be only used to compare versions returned by same API.
/// </summary>
public readonly struct VersionStamp : IEquatable<VersionStamp>, IObjectWritable
{
public static VersionStamp Default => default;
private const int GlobalVersionMarker = -1;
private const int InitialGlobalVersion = 10000;
/// <summary>
/// global counter to avoid collision within same session.
/// it starts with a big initial number just for a clarity in debugging
/// </summary>
private static int s_globalVersion = InitialGlobalVersion;
/// <summary>
/// time stamp
/// </summary>
private readonly DateTime _utcLastModified;
/// <summary>
/// indicate whether there was a collision on same item
/// </summary>
private readonly int _localIncrement;
/// <summary>
/// unique version in same session
/// </summary>
private readonly int _globalIncrement;
private VersionStamp(DateTime utcLastModified)
: this(utcLastModified, 0)
{
}
private VersionStamp(DateTime utcLastModified, int localIncrement)
: this(utcLastModified, localIncrement, GetNextGlobalVersion())
{
}
private VersionStamp(DateTime utcLastModified, int localIncrement, int globalIncrement)
{
if (utcLastModified != default && utcLastModified.Kind != DateTimeKind.Utc)
{
throw new ArgumentException(WorkspacesResources.DateTimeKind_must_be_Utc, nameof(utcLastModified));
}
_utcLastModified = utcLastModified;
_localIncrement = localIncrement;
_globalIncrement = globalIncrement;
}
/// <summary>
/// Creates a new instance of a VersionStamp.
/// </summary>
public static VersionStamp Create()
=> new(DateTime.UtcNow);
/// <summary>
/// Creates a new instance of a version stamp based on the specified DateTime.
/// </summary>
public static VersionStamp Create(DateTime utcTimeLastModified)
=> new(utcTimeLastModified);
/// <summary>
/// compare two different versions and return either one of the versions if there is no collision, otherwise, create a new version
/// that can be used later to compare versions between different items
/// </summary>
public VersionStamp GetNewerVersion(VersionStamp version)
{
// * NOTE *
// in current design/implementation, there are 4 possible ways for a version to be created.
//
// 1. created from a file stamp (most likely by starting a new session). "increment" will have 0 as value
// 2. created by modifying existing item (text changes, project changes etc).
// "increment" will have either 0 or previous increment + 1 if there was a collision.
// 3. created from deserialization (probably by using persistent service).
// 4. created by accumulating versions of multiple items.
//
// and this method is the one that is responsible for #4 case.
if (_utcLastModified > version._utcLastModified)
{
return this;
}
if (_utcLastModified == version._utcLastModified)
{
var thisGlobalVersion = GetGlobalVersion(this);
var thatGlobalVersion = GetGlobalVersion(version);
if (thisGlobalVersion == thatGlobalVersion)
{
// given versions are same one
return this;
}
// mark it as global version
// global version can't be moved to newer version.
return new VersionStamp(_utcLastModified, (thisGlobalVersion > thatGlobalVersion) ? thisGlobalVersion : thatGlobalVersion, GlobalVersionMarker);
}
return version;
}
/// <summary>
/// Gets a new VersionStamp that is guaranteed to be newer than its base one
/// this should only be used for same item to move it to newer version
/// </summary>
public VersionStamp GetNewerVersion()
{
// global version can't be moved to newer version
Debug.Assert(_globalIncrement != GlobalVersionMarker);
var now = DateTime.UtcNow;
var incr = (now == _utcLastModified) ? _localIncrement + 1 : 0;
return new VersionStamp(now, incr);
}
/// <summary>
/// Returns the serialized text form of the VersionStamp.
/// </summary>
public override string ToString()
{
// 'o' is the roundtrip format that captures the most detail.
return _utcLastModified.ToString("o") + "-" + _globalIncrement + "-" + _localIncrement;
}
public override int GetHashCode()
=> Hash.Combine(_utcLastModified.GetHashCode(), _localIncrement);
public override bool Equals(object? obj)
{
if (obj is VersionStamp v)
{
return this.Equals(v);
}
return false;
}
public bool Equals(VersionStamp version)
{
if (_utcLastModified == version._utcLastModified)
{
return GetGlobalVersion(this) == GetGlobalVersion(version);
}
return false;
}
public static bool operator ==(VersionStamp left, VersionStamp right)
=> left.Equals(right);
public static bool operator !=(VersionStamp left, VersionStamp right)
=> !left.Equals(right);
/// <summary>
/// Check whether given persisted version is re-usable. Used by VS for Mac
/// </summary>
internal static bool CanReusePersistedVersion(VersionStamp baseVersion, VersionStamp persistedVersion)
{
if (baseVersion == persistedVersion)
{
return true;
}
// there was a collision, we can't use these
if (baseVersion._localIncrement != 0 || persistedVersion._localIncrement != 0)
{
return false;
}
return baseVersion._utcLastModified == persistedVersion._utcLastModified;
}
bool IObjectWritable.ShouldReuseInSerialization => true;
void IObjectWritable.WriteTo(ObjectWriter writer)
=> WriteTo(writer);
internal void WriteTo(ObjectWriter writer)
{
writer.WriteInt64(_utcLastModified.ToBinary());
writer.WriteInt32(_localIncrement);
writer.WriteInt32(_globalIncrement);
}
internal static VersionStamp ReadFrom(ObjectReader reader)
{
var raw = reader.ReadInt64();
var localIncrement = reader.ReadInt32();
var globalIncrement = reader.ReadInt32();
return new VersionStamp(DateTime.FromBinary(raw), localIncrement, globalIncrement);
}
private static int GetGlobalVersion(VersionStamp version)
{
// global increment < 0 means it is a global version which has its global increment in local increment
return version._globalIncrement >= 0 ? version._globalIncrement : version._localIncrement;
}
private static int GetNextGlobalVersion()
{
// REVIEW: not sure what is best way to wrap it when it overflows. should I just throw or don't care.
// with 50ms (typing) as an interval for a new version, it gives more than 1 year before int32 to overflow.
// with 5ms as an interval, it gives more than 120 days before it overflows.
// since global version is only for per VS session, I think we don't need to worry about overflow.
// or we could use Int64 which will give more than a million years turn around even on 1ms interval.
// this will let versions to be compared safely between multiple items
// without worrying about collision within same session
var globalVersion = Interlocked.Increment(ref VersionStamp.s_globalVersion);
return globalVersion;
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly VersionStamp _versionStamp;
public TestAccessor(in VersionStamp versionStamp)
=> _versionStamp = versionStamp;
/// <summary>
/// True if this VersionStamp is newer than the specified one.
/// </summary>
internal bool IsNewerThan(in VersionStamp version)
{
if (_versionStamp._utcLastModified > version._utcLastModified)
{
return true;
}
if (_versionStamp._utcLastModified == version._utcLastModified)
{
return GetGlobalVersion(_versionStamp) > GetGlobalVersion(version);
}
return false;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ICompoundAssignmentOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_NullArgumentToGetConversionThrows()
{
ICompoundAssignmentOperation nullAssignment = null;
Assert.Throws<ArgumentNullException>("compoundAssignment", () => nullAssignment.GetInConversion());
Assert.Throws<ArgumentNullException>("compoundAssignment", () => nullAssignment.GetOutConversion());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_GetConversionOnValidNode_IdentityConversion()
{
string source = @"
class C
{
static void M()
{
int x = 1, y = 1;
/*<bind>*/x += y/*</bind>*/;
}
}
";
var syntaxTree = Parse(source);
var compilation = CreateCompilationWithMscorlib45(new[] { syntaxTree });
(IOperation operation, _) = GetOperationAndSyntaxForTest<AssignmentExpressionSyntax>(compilation);
var compoundAssignment = (ICompoundAssignmentOperation)operation;
Assert.Equal(Conversion.Identity, compoundAssignment.GetInConversion());
Assert.Equal(Conversion.Identity, compoundAssignment.GetOutConversion());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_GetConversionOnValidNode_InOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
var syntaxTree = Parse(source);
var compilation = CreateCompilationWithMscorlib45(new[] { syntaxTree });
(IOperation operation, SyntaxNode node) = GetOperationAndSyntaxForTest<AssignmentExpressionSyntax>(compilation);
var compoundAssignment = (ICompoundAssignmentOperation)operation;
var typeSymbol = compilation.GetTypeByMetadataName("C");
var implicitSymbols = typeSymbol.GetMembers("op_Implicit").Cast<MethodSymbol>();
var inSymbol = implicitSymbols.Where(sym => sym.ReturnType.SpecialType == SpecialType.System_Int32).Single();
var outSymbol = implicitSymbols.Where(sym => sym != inSymbol).Single();
var inConversion = new Conversion(ConversionKind.ImplicitUserDefined, inSymbol, false);
var outConversion = new Conversion(ConversionKind.ImplicitUserDefined, outSymbol, false);
Assert.Equal(inConversion, compoundAssignment.GetInConversion());
Assert.Equal(outConversion, compoundAssignment.GetOutConversion());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_BinaryOperatorInOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_BinaryOperatorInConversion_InvalidMissingOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C, IsInvalid) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'int' to 'C'
// /*<bind>*/c += x/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c += x").WithArguments("int", "C").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_BinaryOperatorOutConversion_InvalidMissingInConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.None) (OperationKind.CompoundAssignment, Type: ?, IsInvalid) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0019: Operator '+=' cannot be applied to operands of type 'C' and 'int'
// /*<bind>*/c += x/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c += x").WithArguments("+=", "C", "int").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_InConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
public static C operator +(int c1, C c2)
{
return null;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: C C.op_Addition(System.Int32 c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_OutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
public static int operator +(C c1, C c2)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 C.op_Addition(C c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_InOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
public static int operator +(int c1, C c2)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 C.op_Addition(System.Int32 c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_InvalidMissingInConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static int operator +(int c1, C c2)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.None) (OperationKind.CompoundAssignment, Type: ?, IsInvalid) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0019: Operator '+=' cannot be applied to operands of type 'C' and 'int'
// /*<bind>*/c += x/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c += x").WithArguments("+=", "C", "int").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_InvalidMissingOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator int(C c)
{
return 0;
}
public static int operator +(int c1, C c2)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C, IsInvalid) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'int' to 'C'
// /*<bind>*/c += x/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c += x").WithArguments("int", "C").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_01()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] += b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] += b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] += b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_02()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] -= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] -= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] -= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_03()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] *= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] *= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] *= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_04()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] /= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] /= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] /= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_05()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] %= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] %= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] %= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_06()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] &= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] &= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] &= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_07()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] |= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] |= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] |= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_08()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] ^= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] ^= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] ^= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_09()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] <<= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] <<= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] <<= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_10()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] >>= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] >>= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] >>= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ICompoundAssignmentOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_NullArgumentToGetConversionThrows()
{
ICompoundAssignmentOperation nullAssignment = null;
Assert.Throws<ArgumentNullException>("compoundAssignment", () => nullAssignment.GetInConversion());
Assert.Throws<ArgumentNullException>("compoundAssignment", () => nullAssignment.GetOutConversion());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_GetConversionOnValidNode_IdentityConversion()
{
string source = @"
class C
{
static void M()
{
int x = 1, y = 1;
/*<bind>*/x += y/*</bind>*/;
}
}
";
var syntaxTree = Parse(source);
var compilation = CreateCompilationWithMscorlib45(new[] { syntaxTree });
(IOperation operation, _) = GetOperationAndSyntaxForTest<AssignmentExpressionSyntax>(compilation);
var compoundAssignment = (ICompoundAssignmentOperation)operation;
Assert.Equal(Conversion.Identity, compoundAssignment.GetInConversion());
Assert.Equal(Conversion.Identity, compoundAssignment.GetOutConversion());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_GetConversionOnValidNode_InOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
var syntaxTree = Parse(source);
var compilation = CreateCompilationWithMscorlib45(new[] { syntaxTree });
(IOperation operation, SyntaxNode node) = GetOperationAndSyntaxForTest<AssignmentExpressionSyntax>(compilation);
var compoundAssignment = (ICompoundAssignmentOperation)operation;
var typeSymbol = compilation.GetTypeByMetadataName("C");
var implicitSymbols = typeSymbol.GetMembers("op_Implicit").Cast<MethodSymbol>();
var inSymbol = implicitSymbols.Where(sym => sym.ReturnType.SpecialType == SpecialType.System_Int32).Single();
var outSymbol = implicitSymbols.Where(sym => sym != inSymbol).Single();
var inConversion = new Conversion(ConversionKind.ImplicitUserDefined, inSymbol, false);
var outConversion = new Conversion(ConversionKind.ImplicitUserDefined, outSymbol, false);
Assert.Equal(inConversion, compoundAssignment.GetInConversion());
Assert.Equal(outConversion, compoundAssignment.GetOutConversion());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_BinaryOperatorInOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_BinaryOperatorInConversion_InvalidMissingOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator int(C c)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C, IsInvalid) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'int' to 'C'
// /*<bind>*/c += x/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c += x").WithArguments("int", "C").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_BinaryOperatorOutConversion_InvalidMissingInConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.None) (OperationKind.CompoundAssignment, Type: ?, IsInvalid) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0019: Operator '+=' cannot be applied to operands of type 'C' and 'int'
// /*<bind>*/c += x/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c += x").WithArguments("+=", "C", "int").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_InConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
public static C operator +(int c1, C c2)
{
return null;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: C C.op_Addition(System.Int32 c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_OutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
public static int operator +(C c1, C c2)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 C.op_Addition(C c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_InOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static implicit operator int(C c)
{
return 0;
}
public static int operator +(int c1, C c2)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 C.op_Addition(System.Int32 c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i))
Operand:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_InvalidMissingInConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator C(int i)
{
return null;
}
public static int operator +(int c1, C c2)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.None) (OperationKind.CompoundAssignment, Type: ?, IsInvalid) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0019: Operator '+=' cannot be applied to operands of type 'C' and 'int'
// /*<bind>*/c += x/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "c += x").WithArguments("+=", "C", "int").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ICompoundAssignment_UserDefinedBinaryOperator_InvalidMissingOutConversion()
{
string source = @"
class C
{
static void M()
{
var c = new C();
var x = 1;
/*<bind>*/c += x/*</bind>*/;
}
public static implicit operator int(C c)
{
return 0;
}
public static int operator +(int c1, C c2)
{
return 0;
}
}
";
string expectedOperationTree = @"
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C, IsInvalid) (Syntax: 'c += x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c))
OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'int' to 'C'
// /*<bind>*/c += x/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c += x").WithArguments("int", "C").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_01()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] += b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] += b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] += b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_02()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] -= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] -= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] -= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_03()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] *= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] *= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] *= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_04()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] /= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] /= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] /= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_05()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] %= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] %= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] %= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_06()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] &= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] &= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] &= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_07()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] |= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] |= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] |= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_08()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] ^= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] ^= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] ^= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_09()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] <<= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] <<= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] <<= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CompoundAssignment_10()
{
string source = @"
using System;
class C
{
void M(int[] a, int? b, int c)
/*<bind>*/{
a[0] >>= b ?? c;
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]')
Array reference:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a')
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] >>= b ?? c;')
Expression:
ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] >>= b ?? c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/VisualStudio/Core/Def/EditorConfigSettings/Common/EnumSettingViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal abstract class EnumSettingViewModel<T> : IEnumSettingViewModel
where T : Enum
{
private readonly IReadOnlyDictionary<string, T> _mapping;
protected EnumSettingViewModel()
{
_mapping = GetValuesAndDescriptions();
}
public void ChangeProperty(string propertyDescription)
{
if (_mapping.TryGetValue(propertyDescription, out var value))
{
ChangePropertyTo(value);
}
}
public string[] GetValueDescriptions()
=> _mapping.Keys.ToArray();
public int GetValueIndex()
{
var value = GetCurrentValue();
return _mapping.Values.ToList().IndexOf(value);
}
protected abstract IReadOnlyDictionary<string, T> GetValuesAndDescriptions();
protected abstract void ChangePropertyTo(T newValue);
protected abstract T GetCurrentValue();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal abstract class EnumSettingViewModel<T> : IEnumSettingViewModel
where T : Enum
{
private readonly IReadOnlyDictionary<string, T> _mapping;
protected EnumSettingViewModel()
{
_mapping = GetValuesAndDescriptions();
}
public void ChangeProperty(string propertyDescription)
{
if (_mapping.TryGetValue(propertyDescription, out var value))
{
ChangePropertyTo(value);
}
}
public string[] GetValueDescriptions()
=> _mapping.Keys.ToArray();
public int GetValueIndex()
{
var value = GetCurrentValue();
return _mapping.Values.ToList().IndexOf(value);
}
protected abstract IReadOnlyDictionary<string, T> GetValuesAndDescriptions();
protected abstract void ChangePropertyTo(T newValue);
protected abstract T GetCurrentValue();
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LocalAndMethod.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using System;
using System.Collections.ObjectModel;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// The name of a local or argument and the name of
/// the corresponding method to access that object.
/// </summary>
internal abstract class LocalAndMethod
{
public readonly string LocalName;
public readonly string LocalDisplayName;
public readonly string MethodName;
public readonly DkmClrCompilationResultFlags Flags;
public LocalAndMethod(string localName, string localDisplayName, string methodName, DkmClrCompilationResultFlags flags)
{
this.LocalName = localName;
this.LocalDisplayName = localDisplayName;
this.MethodName = methodName;
this.Flags = flags;
}
public abstract Guid GetCustomTypeInfo(out ReadOnlyCollection<byte>? payload);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using System;
using System.Collections.ObjectModel;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// The name of a local or argument and the name of
/// the corresponding method to access that object.
/// </summary>
internal abstract class LocalAndMethod
{
public readonly string LocalName;
public readonly string LocalDisplayName;
public readonly string MethodName;
public readonly DkmClrCompilationResultFlags Flags;
public LocalAndMethod(string localName, string localDisplayName, string methodName, DkmClrCompilationResultFlags flags)
{
this.LocalName = localName;
this.LocalDisplayName = localDisplayName;
this.MethodName = methodName;
this.Flags = flags;
}
public abstract Guid GetCustomTypeInfo(out ReadOnlyCollection<byte>? payload);
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/EditorFeatures/CSharpTest/DocumentationComments/DocumentationCommentTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Editor.CSharp.DocumentationComments;
using Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.DocumentationComments
{
public class DocumentationCommentTests : AbstractDocumentationCommentTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Class()
{
var code =
@"//$$
class C
{
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Record()
{
var code =
@"//$$
record R;";
var expected =
@"/// <summary>
/// $$
/// </summary>
record R;";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_RecordStruct()
{
var code =
@"//$$
record struct R;";
var expected =
@"/// <summary>
/// $$
/// </summary>
record struct R;";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_RecordWithPositionalParameters()
{
var code =
@"//$$
record R(string S, int I);";
var expected =
@"/// <summary>
/// $$
/// </summary>
/// <param name=""S""></param>
/// <param name=""I""></param>
record R(string S, int I);";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_RecordStructWithPositionalParameters()
{
var code =
@"//$$
record struct R(string S, int I);";
var expected =
@"/// <summary>
/// $$
/// </summary>
/// <param name=""S""></param>
/// <param name=""I""></param>
record struct R(string S, int I);";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Class_NewLine()
{
var code = "//$$\r\nclass C\r\n{\r\n}";
var expected = "/// <summary>\n/// $$\n/// </summary>\r\nclass C\r\n{\r\n}";
VerifyTypingCharacter(code, expected, newLine: "\n");
code = "//$$\r\nclass C\r\n{\r\n}";
expected = "/// <summary>\r\n/// $$\r\n/// </summary>\r\nclass C\r\n{\r\n}";
VerifyTypingCharacter(code, expected, newLine: "\r\n");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Class_AutoGenerateXmlDocCommentsOff()
{
var code =
@"//$$
class C
{
}";
var expected =
@"///$$
class C
{
}";
VerifyTypingCharacter(code, expected, autoGenerateXmlDocComments: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Method()
{
var code =
@"class C
{
//$$
int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<T>(int goo) { return 0; }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(54245, "https://github.com/dotnet/roslyn/issues/54245")]
public void TypingCharacter_Method_WithExceptions()
{
var code =
@"class C
{
//$$
int M<T>(int goo)
{
if (goo < 0) throw new /*leading trivia*/Exception/*trailing trivia*/();
return 0;
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
/// <exception cref=""Exception""></exception>
int M<T>(int goo)
{
if (goo < 0) throw new /*leading trivia*/Exception/*trailing trivia*/();
return 0;
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(54245, "https://github.com/dotnet/roslyn/issues/54245")]
public void TypingCharacter_Constructor_WithExceptions()
{
var code =
@"class C
{
//$$
public C(int goo)
{
if (goo < 0) throw new /*leading trivia*/Exception/*trailing trivia*/();
throw null;
throw null;
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <param name=""goo""></param>
/// <exception cref=""Exception""></exception>
/// <exception cref=""System.NullReferenceException""></exception>
public C(int goo)
{
if (goo < 0) throw new /*leading trivia*/Exception/*trailing trivia*/();
throw null;
throw null;
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(54245, "https://github.com/dotnet/roslyn/issues/54245")]
public void TypingCharacter_Constructor_WithExceptions_Caught()
{
// This result is wrong, but we can't do better as long as we only check syntax.
var code = @"
using System;
class C
{
//$$
public C(int goo)
{
try
{
if (goo == 10)
throw new Exception();
if (goo == 9)
throw new ArgumentOutOfRangeException();
}
catch (ArgumentException)
{
}
throw null;
throw null;
}
}";
var expected = @"
using System;
class C
{
/// <summary>
/// $$
/// </summary>
/// <param name=""goo""></param>
/// <exception cref=""Exception""></exception>
/// <exception cref=""ArgumentOutOfRangeException""></exception>
/// <exception cref=""NullReferenceException""></exception>
public C(int goo)
{
try
{
if (goo == 10)
throw new Exception();
if (goo == 9)
throw new ArgumentOutOfRangeException();
}
catch (ArgumentException)
{
}
throw null;
throw null;
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Method_WithVerbatimParams()
{
var code =
@"class C
{
//$$
int M<@int>(int @goo) { return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""int""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<@int>(int @goo) { return 0; }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_AutoProperty()
{
var code =
@"class C
{
//$$
int P { get; set; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
int P { get; set; }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Property()
{
var code =
@"class C
{
//$$
int P
{
get { return 0; }
set { }
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
int P
{
get { return 0; }
set { }
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Indexer()
{
var code =
@"class C
{
//$$
int this[int index]
{
get { return 0; }
set { }
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <param name=""index""></param>
/// <returns></returns>
int this[int index]
{
get { return 0; }
set { }
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_VoidMethod1()
{
var code =
@"class C
{
//$$
void M<T>(int goo) { }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
void M<T>(int goo) { }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_VoidMethod_WithVerbatimParams()
{
var code =
@"class C
{
//$$
void M<@T>(int @int) { }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""int""></param>
void M<@T>(int @int) { }
}";
VerifyTypingCharacter(code, expected);
}
[WorkItem(538699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538699")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_VoidMethod2()
{
var code =
@"class C
{
//$$
void Method() { }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
void Method() { }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists1()
{
var code = @"
///
//$$
class C
{
}";
var expected = @"
///
///$$
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists2()
{
var code = @"
///
//$$
class C
{
}";
var expected = @"
///
///$$
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists3()
{
var code = @"
class B { } ///
//$$
class C
{
}";
var expected = @"
class B { } ///
///$$
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists4()
{
var code =
@"//$$
/// <summary></summary>
class C
{
}";
var expected =
@"///$$
/// <summary></summary>
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists5()
{
var code =
@"class C
{
//$$
/// <summary></summary>
int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
///$$
/// <summary></summary>
int M<T>(int goo) { return 0; }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotInsideMethodBody1()
{
var code =
@"class C
{
void M(int goo)
{
//$$
}
}";
var expected =
@"class C
{
void M(int goo)
{
///$$
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotInsideMethodBody2()
{
var code =
@"class C
{
/// <summary></summary>
void M(int goo)
{
//$$
}
}";
var expected =
@"class C
{
/// <summary></summary>
void M(int goo)
{
///$$
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotAfterClassName()
{
var code =
@"class C//$$
{
}";
var expected =
@"class C///$$
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotAfterOpenBrace()
{
var code =
@"class C
{//$$
}";
var expected =
@"class C
{///$$
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotAfterCtorName()
{
var code =
@"class C
{
C() //$$
}";
var expected =
@"class C
{
C() ///$$
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotInsideCtor()
{
var code =
@"class C
{
C()
{
//$$
}
}";
var expected =
@"class C
{
C()
{
///$$
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Class1()
{
var code =
@"///$$
class C
{
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Class1_AutoGenerateXmlDocCommentsOff()
{
var code =
@"///$$
class C
{
}";
var expected =
@"///
$$
class C
{
}";
VerifyPressingEnter(code, expected, autoGenerateXmlDocComments: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Class2()
{
var code =
@"///$$class C
{
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Class3()
{
var code =
@"///$$[Goo] class C
{
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
[Goo] class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_NotAfterWhitespace()
{
var code =
@"/// $$class C
{
}";
var expected =
@"///
/// $$class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Method1()
{
var code =
@"class C
{
///$$
int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<T>(int goo) { return 0; }
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Method2()
{
var code =
@"class C
{
///$$int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<T>(int goo) { return 0; }
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInMethodBody1()
{
var code =
@"class C
{
void Goo()
{
///$$
}
}";
var expected =
@"class C
{
void Goo()
{
///
$$
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInterleavedInClassName1()
{
var code =
@"class///$$ C
{
}";
var expected =
@"class///
$$ C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInterleavedInClassName2()
{
var code =
@"class ///$$C
{
}";
var expected =
@"class ///
$$C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInterleavedInClassName3()
{
var code =
@"class /// $$C
{
}";
var expected =
@"class ///
$$C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537514, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537514")]
[WorkItem(537532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537532")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotAfterClassName1()
{
var code =
@"class C ///$$
{
}";
var expected =
@"class C ///
$$
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537552")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotAfterClassName2()
{
var code =
@"class C /** $$
{
}";
var expected =
@"class C /**
$$
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537535")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotAfterCtorName()
{
var code =
@"class C
{
C() ///$$
}";
var expected =
@"class C
{
C() ///
$$
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537511")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInsideCtor()
{
var code =
@"class C
{
C()
{
///$$
}
}";
var expected =
@"class C
{
C()
{
///
$$
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537550")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotBeforeDocComment()
{
var code =
@" class c1
{
$$/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task goo()
{
var x = 1;
}
}";
var expected =
@" class c1
{
$$/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task goo()
{
var x = 1;
}
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes1()
{
var code =
@"///$$
/// <summary></summary>
class C
{
}";
var expected =
@"///
/// $$
/// <summary></summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes2()
{
var code =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
var expected =
@"/// <summary>
///
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes3()
{
var code =
@" /// <summary>
/// $$
/// </summary>
class C
{
}";
var expected =
@" /// <summary>
///
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes4()
{
var code =
@"/// <summary>$$</summary>
class C
{
}";
var expected =
@"/// <summary>
/// $$</summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes5()
{
var code =
@" /// <summary>
/// $$
/// </summary>
class C
{
}";
var expected =
@" /// <summary>
///
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes6()
{
var code =
@"/// <summary></summary>$$
class C
{
}";
var expected =
@"/// <summary></summary>
/// $$
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes7()
{
var code =
@" /// <summary>$$</summary>
class C
{
}";
var expected =
@" /// <summary>
/// $$</summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(538702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538702")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes8()
{
var code =
@"/// <summary>
///
/// </summary>
///$$class C {}";
var expected =
@"/// <summary>
///
/// </summary>
///
/// $$class C {}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes9()
{
var code =
@"class C
{
///$$
/// <summary></summary>
int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
///
/// $$
/// <summary></summary>
int M<T>(int goo) { return 0; }
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes10()
{
var code =
@"/// <summary>
///
/// </summary>
///$$Go ahead and add some slashes";
var expected =
@"/// <summary>
///
/// </summary>
///
/// $$Go ahead and add some slashes";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes11()
{
var code =
@"class C
{
/// <summary>
///
/// </summary>
/// <param name=""i"">$$</param>
void Goo(int i)
{
}
}";
var expected =
@"class C
{
/// <summary>
///
/// </summary>
/// <param name=""i"">
/// $$</param>
void Goo(int i)
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes12_AutoGenerateXmlDocCommentsOff()
{
var code =
@"///$$
/// <summary></summary>
class C
{
}";
var expected =
@"///
/// $$
/// <summary></summary>
class C
{
}";
VerifyPressingEnter(code, expected, autoGenerateXmlDocComments: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_DontInsertSlashes1()
{
var code =
@"/// <summary></summary>
/// $$
class C
{
}";
var expected =
@"/// <summary></summary>
///
$$
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(538701, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538701")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_DontInsertSlashes2()
{
var code =
@"///<summary></summary>
///$$
class C{}";
var expected =
@"///<summary></summary>
///
$$
class C{}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(25746, "https://github.com/dotnet/roslyn/issues/25746")]
public void PressingEnter_ExtraSlashesAfterExteriorTrivia()
{
var code =
@"class C
{
C()
{
//////$$
}
}";
var expected =
@"class C
{
C()
{
//////
///$$
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(542426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542426")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_PreserveParams()
{
var code =
@"/// <summary>
///
/// </summary>
/// <param name=""args"">$$</param>
static void Main(string[] args)
{ }";
var expected =
@"/// <summary>
///
/// </summary>
/// <param name=""args"">
/// $$</param>
static void Main(string[] args)
{ }";
VerifyPressingEnter(code, expected);
}
[WorkItem(2091, "https://github.com/dotnet/roslyn/issues/2091")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InTextBeforeSpace()
{
const string code =
@"class C
{
/// <summary>
/// hello$$ world
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello
/// $$world
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation1()
{
const string code =
@"class C
{
/// <summary>
/// hello world$$
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello world
/// $$
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation2()
{
const string code =
@"class C
{
/// <summary>
/// hello $$world
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello
/// $$world
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation3()
{
const string code =
@"class C
{
/// <summary>
/// hello$$ world
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello
/// $$world
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation4()
{
const string code =
@"class C
{
/// <summary>
/// $$hello world
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
///
/// $$hello world
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation5_UseTabs()
{
const string code =
@"class C
{
/// <summary>
/// hello world$$
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello world
/// $$
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected, useTabs: true);
}
[WorkItem(5486, "https://github.com/dotnet/roslyn/issues/5486")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Selection1()
{
var code =
@"/// <summary>
/// Hello [|World|]$$!
/// </summary>
class C
{
}";
var expected =
@"/// <summary>
/// Hello
/// $$!
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(5486, "https://github.com/dotnet/roslyn/issues/5486")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Selection2()
{
var code =
@"/// <summary>
/// Hello $$[|World|]!
/// </summary>
class C
{
}";
var expected =
@"/// <summary>
/// Hello
/// $$!
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(27223, "https://github.com/dotnet/roslyn/issues/27223")]
public void PressingEnter_XmldocInStringLiteral()
{
var code =
@"class C
{
C()
{
string s = @""
/// <summary>$$</summary>
void M() {}""
}
}";
var expected =
@"class C
{
C()
{
string s = @""
/// <summary>
/// $$</summary>
void M() {}""
}
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Class()
{
var code =
@"class C
{$$
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Record()
{
var code = "record R$$;";
var expected =
@"/// <summary>
/// $$
/// </summary>
record R;";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_RecordStruct()
{
var code = "record struct R$$;";
var expected =
@"/// <summary>
/// $$
/// </summary>
record struct R;";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_RecordWithPositionalParameters()
{
var code = "record R$$(string S, int I);";
var expected =
@"/// <summary>
/// $$
/// </summary>
/// <param name=""S""></param>
/// <param name=""I""></param>
record R(string S, int I);";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_RecordStructWithPositionalParameters()
{
var code = "record struct R$$(string S, int I);";
var expected =
@"/// <summary>
/// $$
/// </summary>
/// <param name=""S""></param>
/// <param name=""I""></param>
record struct R(string S, int I);";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Class_AutoGenerateXmlDocCommentsOff()
{
var code =
@"class C
{$$
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyInsertCommentCommand(code, expected, autoGenerateXmlDocComments: false);
}
[WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_BeforeClass1()
{
var code =
@"$$
class C { }";
var expected =
@"
/// <summary>
/// $$
/// </summary>
class C { }";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_BeforeClass2()
{
var code =
@"class B { }
$$
class C { }";
var expected =
@"class B { }
/// <summary>
/// $$
/// </summary>
class C { }";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_BeforeClass3()
{
var code =
@"class B
{
$$
class C { }
}";
var expected =
@"class B
{
/// <summary>
/// $$
/// </summary>
class C { }
}";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(527604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527604")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Class_NotIfMultilineDocCommentExists()
{
var code =
@"/**
*/
class C { $$ }";
var expected =
@"/**
*/
class C { $$ }";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Method()
{
var code =
@"class C
{
int M<T>(int goo) { $$return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<T>(int goo) { return 0; }
}";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Class_NotIfCommentExists()
{
var code =
@"/// <summary></summary>
class C
{$$
}";
var expected =
@"/// <summary></summary>
class C
{$$
}";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Method_NotIfCommentExists()
{
var code =
@"class C
{
/// <summary></summary>
int M<T>(int goo) { $$return 0; }
}";
var expected =
@"class C
{
/// <summary></summary>
int M<T>(int goo) { $$return 0; }
}";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_FirstClassOnLine()
{
var code = @"$$class C { } class D { }";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C { } class D { }";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_NotOnSecondClassOnLine()
{
var code = @"class C { } $$class D { }";
var expected = @"class C { } $$class D { }";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_FirstMethodOnLine()
{
var code =
@"class C
{
protected abstract void $$Goo(); protected abstract void Bar();
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
protected abstract void Goo(); protected abstract void Bar();
}";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_NotOnSecondMethodOnLine()
{
var code =
@"class C
{
protected abstract void Goo(); protected abstract void $$Bar();
}";
var expected =
@"class C
{
protected abstract void Goo(); protected abstract void $$Bar();
}";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(917904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/917904")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestUseTab()
{
var code =
@"using System;
public class Class1
{
//$$
public Class1()
{
}
}";
var expected =
@"using System;
public class Class1
{
/// <summary>
/// $$
/// </summary>
public Class1()
{
}
}";
VerifyTypingCharacter(code, expected, useTabs: true);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineAbove1()
{
const string code =
@"class C
{
/// <summary>
/// stuff$$
/// </summary>
void M()
{
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// stuff
/// </summary>
void M()
{
}
}";
VerifyOpenLineAbove(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineAbove2()
{
const string code =
@"class C
{
/// <summary>
/// $$stuff
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// $$
/// stuff
/// </summary>
void M()
{
}
}";
VerifyOpenLineAbove(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineAbove3()
{
const string code =
@"class C
{
/// $$<summary>
/// stuff
/// </summary>
void M()
{
}
}";
// Note that the caret position specified below does not look correct because
// it is in virtual space in this case.
const string expected =
@"class C
{
$$
/// <summary>
/// stuff
/// </summary>
void M()
{
}
}";
VerifyOpenLineAbove(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineAbove4_Tabs()
{
const string code =
@"class C
{
/// <summary>
/// $$stuff
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// $$
/// stuff
/// </summary>
void M()
{
}
}";
VerifyOpenLineAbove(code, expected, useTabs: true);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineBelow1()
{
const string code =
@"class C
{
/// <summary>
/// stuff$$
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// stuff
/// $$
/// </summary>
void M()
{
}
}";
VerifyOpenLineBelow(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineBelow2()
{
const string code =
@"class C
{
/// <summary>
/// $$stuff
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// stuff
/// $$
/// </summary>
void M()
{
}
}";
VerifyOpenLineBelow(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineBelow3()
{
const string code =
@"/// <summary>
/// stuff
/// $$</summary>
";
const string expected =
@"/// <summary>
/// stuff
/// </summary>
/// $$
";
VerifyOpenLineBelow(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineBelow4_Tabs()
{
const string code =
@"class C
{
/// <summary>
/// $$stuff
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// stuff
/// $$
/// </summary>
void M()
{
}
}";
VerifyOpenLineBelow(code, expected, useTabs: true);
}
[WorkItem(468638, @"https://devdiv.visualstudio.com/DevDiv/NET%20Developer%20Experience%20IDE/_workitems/edit/468638")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void VerifyEnterWithTrimNewLineEditorConfigOption()
{
const string code =
@"/// <summary>
/// $$
/// </summary>
class C { }";
const string expected =
@"/// <summary>
///
/// $$
/// </summary>
class C { }";
try
{
VerifyPressingEnter(code, expected, useTabs: true, setOptionsOpt:
workspace =>
{
workspace.GetService<IEditorOptionsFactoryService>().GlobalOptions
.SetOptionValue(DefaultOptions.TrimTrailingWhiteSpaceOptionName, true);
});
}
finally
{
TestWorkspace.CreateCSharp("").GetService<IEditorOptionsFactoryService>().GlobalOptions
.SetOptionValue(DefaultOptions.TrimTrailingWhiteSpaceOptionName, false);
}
}
protected override char DocumentationCommentCharacter
{
get { return '/'; }
}
internal override ICommandHandler CreateCommandHandler(TestWorkspace workspace)
{
return workspace.ExportProvider.GetCommandHandler<DocumentationCommentCommandHandler>(PredefinedCommandHandlerNames.DocumentationComments, ContentTypeNames.CSharpContentType);
}
protected override TestWorkspace CreateTestWorkspace(string code)
=> TestWorkspace.CreateCSharp(code);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Editor.CSharp.DocumentationComments;
using Microsoft.CodeAnalysis.Editor.UnitTests.DocumentationComments;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.DocumentationComments
{
public class DocumentationCommentTests : AbstractDocumentationCommentTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Class()
{
var code =
@"//$$
class C
{
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Record()
{
var code =
@"//$$
record R;";
var expected =
@"/// <summary>
/// $$
/// </summary>
record R;";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_RecordStruct()
{
var code =
@"//$$
record struct R;";
var expected =
@"/// <summary>
/// $$
/// </summary>
record struct R;";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_RecordWithPositionalParameters()
{
var code =
@"//$$
record R(string S, int I);";
var expected =
@"/// <summary>
/// $$
/// </summary>
/// <param name=""S""></param>
/// <param name=""I""></param>
record R(string S, int I);";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_RecordStructWithPositionalParameters()
{
var code =
@"//$$
record struct R(string S, int I);";
var expected =
@"/// <summary>
/// $$
/// </summary>
/// <param name=""S""></param>
/// <param name=""I""></param>
record struct R(string S, int I);";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Class_NewLine()
{
var code = "//$$\r\nclass C\r\n{\r\n}";
var expected = "/// <summary>\n/// $$\n/// </summary>\r\nclass C\r\n{\r\n}";
VerifyTypingCharacter(code, expected, newLine: "\n");
code = "//$$\r\nclass C\r\n{\r\n}";
expected = "/// <summary>\r\n/// $$\r\n/// </summary>\r\nclass C\r\n{\r\n}";
VerifyTypingCharacter(code, expected, newLine: "\r\n");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Class_AutoGenerateXmlDocCommentsOff()
{
var code =
@"//$$
class C
{
}";
var expected =
@"///$$
class C
{
}";
VerifyTypingCharacter(code, expected, autoGenerateXmlDocComments: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Method()
{
var code =
@"class C
{
//$$
int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<T>(int goo) { return 0; }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(54245, "https://github.com/dotnet/roslyn/issues/54245")]
public void TypingCharacter_Method_WithExceptions()
{
var code =
@"class C
{
//$$
int M<T>(int goo)
{
if (goo < 0) throw new /*leading trivia*/Exception/*trailing trivia*/();
return 0;
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
/// <exception cref=""Exception""></exception>
int M<T>(int goo)
{
if (goo < 0) throw new /*leading trivia*/Exception/*trailing trivia*/();
return 0;
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(54245, "https://github.com/dotnet/roslyn/issues/54245")]
public void TypingCharacter_Constructor_WithExceptions()
{
var code =
@"class C
{
//$$
public C(int goo)
{
if (goo < 0) throw new /*leading trivia*/Exception/*trailing trivia*/();
throw null;
throw null;
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <param name=""goo""></param>
/// <exception cref=""Exception""></exception>
/// <exception cref=""System.NullReferenceException""></exception>
public C(int goo)
{
if (goo < 0) throw new /*leading trivia*/Exception/*trailing trivia*/();
throw null;
throw null;
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(54245, "https://github.com/dotnet/roslyn/issues/54245")]
public void TypingCharacter_Constructor_WithExceptions_Caught()
{
// This result is wrong, but we can't do better as long as we only check syntax.
var code = @"
using System;
class C
{
//$$
public C(int goo)
{
try
{
if (goo == 10)
throw new Exception();
if (goo == 9)
throw new ArgumentOutOfRangeException();
}
catch (ArgumentException)
{
}
throw null;
throw null;
}
}";
var expected = @"
using System;
class C
{
/// <summary>
/// $$
/// </summary>
/// <param name=""goo""></param>
/// <exception cref=""Exception""></exception>
/// <exception cref=""ArgumentOutOfRangeException""></exception>
/// <exception cref=""NullReferenceException""></exception>
public C(int goo)
{
try
{
if (goo == 10)
throw new Exception();
if (goo == 9)
throw new ArgumentOutOfRangeException();
}
catch (ArgumentException)
{
}
throw null;
throw null;
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Method_WithVerbatimParams()
{
var code =
@"class C
{
//$$
int M<@int>(int @goo) { return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""int""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<@int>(int @goo) { return 0; }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_AutoProperty()
{
var code =
@"class C
{
//$$
int P { get; set; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
int P { get; set; }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Property()
{
var code =
@"class C
{
//$$
int P
{
get { return 0; }
set { }
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
int P
{
get { return 0; }
set { }
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_Indexer()
{
var code =
@"class C
{
//$$
int this[int index]
{
get { return 0; }
set { }
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <param name=""index""></param>
/// <returns></returns>
int this[int index]
{
get { return 0; }
set { }
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_VoidMethod1()
{
var code =
@"class C
{
//$$
void M<T>(int goo) { }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
void M<T>(int goo) { }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_VoidMethod_WithVerbatimParams()
{
var code =
@"class C
{
//$$
void M<@T>(int @int) { }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""int""></param>
void M<@T>(int @int) { }
}";
VerifyTypingCharacter(code, expected);
}
[WorkItem(538699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538699")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_VoidMethod2()
{
var code =
@"class C
{
//$$
void Method() { }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
void Method() { }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists1()
{
var code = @"
///
//$$
class C
{
}";
var expected = @"
///
///$$
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists2()
{
var code = @"
///
//$$
class C
{
}";
var expected = @"
///
///$$
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists3()
{
var code = @"
class B { } ///
//$$
class C
{
}";
var expected = @"
class B { } ///
///$$
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists4()
{
var code =
@"//$$
/// <summary></summary>
class C
{
}";
var expected =
@"///$$
/// <summary></summary>
class C
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotWhenDocCommentExists5()
{
var code =
@"class C
{
//$$
/// <summary></summary>
int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
///$$
/// <summary></summary>
int M<T>(int goo) { return 0; }
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotInsideMethodBody1()
{
var code =
@"class C
{
void M(int goo)
{
//$$
}
}";
var expected =
@"class C
{
void M(int goo)
{
///$$
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotInsideMethodBody2()
{
var code =
@"class C
{
/// <summary></summary>
void M(int goo)
{
//$$
}
}";
var expected =
@"class C
{
/// <summary></summary>
void M(int goo)
{
///$$
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotAfterClassName()
{
var code =
@"class C//$$
{
}";
var expected =
@"class C///$$
{
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotAfterOpenBrace()
{
var code =
@"class C
{//$$
}";
var expected =
@"class C
{///$$
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotAfterCtorName()
{
var code =
@"class C
{
C() //$$
}";
var expected =
@"class C
{
C() ///$$
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TypingCharacter_NotInsideCtor()
{
var code =
@"class C
{
C()
{
//$$
}
}";
var expected =
@"class C
{
C()
{
///$$
}
}";
VerifyTypingCharacter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Class1()
{
var code =
@"///$$
class C
{
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Class1_AutoGenerateXmlDocCommentsOff()
{
var code =
@"///$$
class C
{
}";
var expected =
@"///
$$
class C
{
}";
VerifyPressingEnter(code, expected, autoGenerateXmlDocComments: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Class2()
{
var code =
@"///$$class C
{
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Class3()
{
var code =
@"///$$[Goo] class C
{
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
[Goo] class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_NotAfterWhitespace()
{
var code =
@"/// $$class C
{
}";
var expected =
@"///
/// $$class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Method1()
{
var code =
@"class C
{
///$$
int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<T>(int goo) { return 0; }
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertComment_Method2()
{
var code =
@"class C
{
///$$int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<T>(int goo) { return 0; }
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInMethodBody1()
{
var code =
@"class C
{
void Goo()
{
///$$
}
}";
var expected =
@"class C
{
void Goo()
{
///
$$
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInterleavedInClassName1()
{
var code =
@"class///$$ C
{
}";
var expected =
@"class///
$$ C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInterleavedInClassName2()
{
var code =
@"class ///$$C
{
}";
var expected =
@"class ///
$$C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537513")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInterleavedInClassName3()
{
var code =
@"class /// $$C
{
}";
var expected =
@"class ///
$$C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537514, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537514")]
[WorkItem(537532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537532")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotAfterClassName1()
{
var code =
@"class C ///$$
{
}";
var expected =
@"class C ///
$$
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537552")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotAfterClassName2()
{
var code =
@"class C /** $$
{
}";
var expected =
@"class C /**
$$
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537535")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotAfterCtorName()
{
var code =
@"class C
{
C() ///$$
}";
var expected =
@"class C
{
C() ///
$$
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537511")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotInsideCtor()
{
var code =
@"class C
{
C()
{
///$$
}
}";
var expected =
@"class C
{
C()
{
///
$$
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(537550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537550")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_NotBeforeDocComment()
{
var code =
@" class c1
{
$$/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task goo()
{
var x = 1;
}
}";
var expected =
@" class c1
{
$$/// <summary>
///
/// </summary>
/// <returns></returns>
public async Task goo()
{
var x = 1;
}
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes1()
{
var code =
@"///$$
/// <summary></summary>
class C
{
}";
var expected =
@"///
/// $$
/// <summary></summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes2()
{
var code =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
var expected =
@"/// <summary>
///
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes3()
{
var code =
@" /// <summary>
/// $$
/// </summary>
class C
{
}";
var expected =
@" /// <summary>
///
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes4()
{
var code =
@"/// <summary>$$</summary>
class C
{
}";
var expected =
@"/// <summary>
/// $$</summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes5()
{
var code =
@" /// <summary>
/// $$
/// </summary>
class C
{
}";
var expected =
@" /// <summary>
///
/// $$
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes6()
{
var code =
@"/// <summary></summary>$$
class C
{
}";
var expected =
@"/// <summary></summary>
/// $$
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes7()
{
var code =
@" /// <summary>$$</summary>
class C
{
}";
var expected =
@" /// <summary>
/// $$</summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(538702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538702")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes8()
{
var code =
@"/// <summary>
///
/// </summary>
///$$class C {}";
var expected =
@"/// <summary>
///
/// </summary>
///
/// $$class C {}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes9()
{
var code =
@"class C
{
///$$
/// <summary></summary>
int M<T>(int goo) { return 0; }
}";
var expected =
@"class C
{
///
/// $$
/// <summary></summary>
int M<T>(int goo) { return 0; }
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes10()
{
var code =
@"/// <summary>
///
/// </summary>
///$$Go ahead and add some slashes";
var expected =
@"/// <summary>
///
/// </summary>
///
/// $$Go ahead and add some slashes";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes11()
{
var code =
@"class C
{
/// <summary>
///
/// </summary>
/// <param name=""i"">$$</param>
void Goo(int i)
{
}
}";
var expected =
@"class C
{
/// <summary>
///
/// </summary>
/// <param name=""i"">
/// $$</param>
void Goo(int i)
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InsertSlashes12_AutoGenerateXmlDocCommentsOff()
{
var code =
@"///$$
/// <summary></summary>
class C
{
}";
var expected =
@"///
/// $$
/// <summary></summary>
class C
{
}";
VerifyPressingEnter(code, expected, autoGenerateXmlDocComments: false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_DontInsertSlashes1()
{
var code =
@"/// <summary></summary>
/// $$
class C
{
}";
var expected =
@"/// <summary></summary>
///
$$
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(538701, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538701")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_DontInsertSlashes2()
{
var code =
@"///<summary></summary>
///$$
class C{}";
var expected =
@"///<summary></summary>
///
$$
class C{}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(25746, "https://github.com/dotnet/roslyn/issues/25746")]
public void PressingEnter_ExtraSlashesAfterExteriorTrivia()
{
var code =
@"class C
{
C()
{
//////$$
}
}";
var expected =
@"class C
{
C()
{
//////
///$$
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(542426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542426")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_PreserveParams()
{
var code =
@"/// <summary>
///
/// </summary>
/// <param name=""args"">$$</param>
static void Main(string[] args)
{ }";
var expected =
@"/// <summary>
///
/// </summary>
/// <param name=""args"">
/// $$</param>
static void Main(string[] args)
{ }";
VerifyPressingEnter(code, expected);
}
[WorkItem(2091, "https://github.com/dotnet/roslyn/issues/2091")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_InTextBeforeSpace()
{
const string code =
@"class C
{
/// <summary>
/// hello$$ world
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello
/// $$world
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation1()
{
const string code =
@"class C
{
/// <summary>
/// hello world$$
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello world
/// $$
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation2()
{
const string code =
@"class C
{
/// <summary>
/// hello $$world
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello
/// $$world
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation3()
{
const string code =
@"class C
{
/// <summary>
/// hello$$ world
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello
/// $$world
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation4()
{
const string code =
@"class C
{
/// <summary>
/// $$hello world
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
///
/// $$hello world
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(2108, "https://github.com/dotnet/roslyn/issues/2108")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Indentation5_UseTabs()
{
const string code =
@"class C
{
/// <summary>
/// hello world$$
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// hello world
/// $$
/// </summary>
void M()
{
}
}";
VerifyPressingEnter(code, expected, useTabs: true);
}
[WorkItem(5486, "https://github.com/dotnet/roslyn/issues/5486")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Selection1()
{
var code =
@"/// <summary>
/// Hello [|World|]$$!
/// </summary>
class C
{
}";
var expected =
@"/// <summary>
/// Hello
/// $$!
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WorkItem(5486, "https://github.com/dotnet/roslyn/issues/5486")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void PressingEnter_Selection2()
{
var code =
@"/// <summary>
/// Hello $$[|World|]!
/// </summary>
class C
{
}";
var expected =
@"/// <summary>
/// Hello
/// $$!
/// </summary>
class C
{
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
[WorkItem(27223, "https://github.com/dotnet/roslyn/issues/27223")]
public void PressingEnter_XmldocInStringLiteral()
{
var code =
@"class C
{
C()
{
string s = @""
/// <summary>$$</summary>
void M() {}""
}
}";
var expected =
@"class C
{
C()
{
string s = @""
/// <summary>
/// $$</summary>
void M() {}""
}
}";
VerifyPressingEnter(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Class()
{
var code =
@"class C
{$$
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Record()
{
var code = "record R$$;";
var expected =
@"/// <summary>
/// $$
/// </summary>
record R;";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_RecordStruct()
{
var code = "record struct R$$;";
var expected =
@"/// <summary>
/// $$
/// </summary>
record struct R;";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_RecordWithPositionalParameters()
{
var code = "record R$$(string S, int I);";
var expected =
@"/// <summary>
/// $$
/// </summary>
/// <param name=""S""></param>
/// <param name=""I""></param>
record R(string S, int I);";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_RecordStructWithPositionalParameters()
{
var code = "record struct R$$(string S, int I);";
var expected =
@"/// <summary>
/// $$
/// </summary>
/// <param name=""S""></param>
/// <param name=""I""></param>
record struct R(string S, int I);";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(4817, "https://github.com/dotnet/roslyn/issues/4817")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Class_AutoGenerateXmlDocCommentsOff()
{
var code =
@"class C
{$$
}";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C
{
}";
VerifyInsertCommentCommand(code, expected, autoGenerateXmlDocComments: false);
}
[WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_BeforeClass1()
{
var code =
@"$$
class C { }";
var expected =
@"
/// <summary>
/// $$
/// </summary>
class C { }";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_BeforeClass2()
{
var code =
@"class B { }
$$
class C { }";
var expected =
@"class B { }
/// <summary>
/// $$
/// </summary>
class C { }";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538714")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_BeforeClass3()
{
var code =
@"class B
{
$$
class C { }
}";
var expected =
@"class B
{
/// <summary>
/// $$
/// </summary>
class C { }
}";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(527604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527604")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Class_NotIfMultilineDocCommentExists()
{
var code =
@"/**
*/
class C { $$ }";
var expected =
@"/**
*/
class C { $$ }";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Method()
{
var code =
@"class C
{
int M<T>(int goo) { $$return 0; }
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
/// <typeparam name=""T""></typeparam>
/// <param name=""goo""></param>
/// <returns></returns>
int M<T>(int goo) { return 0; }
}";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Class_NotIfCommentExists()
{
var code =
@"/// <summary></summary>
class C
{$$
}";
var expected =
@"/// <summary></summary>
class C
{$$
}";
VerifyInsertCommentCommand(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_Method_NotIfCommentExists()
{
var code =
@"class C
{
/// <summary></summary>
int M<T>(int goo) { $$return 0; }
}";
var expected =
@"class C
{
/// <summary></summary>
int M<T>(int goo) { $$return 0; }
}";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_FirstClassOnLine()
{
var code = @"$$class C { } class D { }";
var expected =
@"/// <summary>
/// $$
/// </summary>
class C { } class D { }";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_NotOnSecondClassOnLine()
{
var code = @"class C { } $$class D { }";
var expected = @"class C { } $$class D { }";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_FirstMethodOnLine()
{
var code =
@"class C
{
protected abstract void $$Goo(); protected abstract void Bar();
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// </summary>
protected abstract void Goo(); protected abstract void Bar();
}";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(538482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538482")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void Command_NotOnSecondMethodOnLine()
{
var code =
@"class C
{
protected abstract void Goo(); protected abstract void $$Bar();
}";
var expected =
@"class C
{
protected abstract void Goo(); protected abstract void $$Bar();
}";
VerifyInsertCommentCommand(code, expected);
}
[WorkItem(917904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/917904")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestUseTab()
{
var code =
@"using System;
public class Class1
{
//$$
public Class1()
{
}
}";
var expected =
@"using System;
public class Class1
{
/// <summary>
/// $$
/// </summary>
public Class1()
{
}
}";
VerifyTypingCharacter(code, expected, useTabs: true);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineAbove1()
{
const string code =
@"class C
{
/// <summary>
/// stuff$$
/// </summary>
void M()
{
}
}";
var expected =
@"class C
{
/// <summary>
/// $$
/// stuff
/// </summary>
void M()
{
}
}";
VerifyOpenLineAbove(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineAbove2()
{
const string code =
@"class C
{
/// <summary>
/// $$stuff
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// $$
/// stuff
/// </summary>
void M()
{
}
}";
VerifyOpenLineAbove(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineAbove3()
{
const string code =
@"class C
{
/// $$<summary>
/// stuff
/// </summary>
void M()
{
}
}";
// Note that the caret position specified below does not look correct because
// it is in virtual space in this case.
const string expected =
@"class C
{
$$
/// <summary>
/// stuff
/// </summary>
void M()
{
}
}";
VerifyOpenLineAbove(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineAbove4_Tabs()
{
const string code =
@"class C
{
/// <summary>
/// $$stuff
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// $$
/// stuff
/// </summary>
void M()
{
}
}";
VerifyOpenLineAbove(code, expected, useTabs: true);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineBelow1()
{
const string code =
@"class C
{
/// <summary>
/// stuff$$
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// stuff
/// $$
/// </summary>
void M()
{
}
}";
VerifyOpenLineBelow(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineBelow2()
{
const string code =
@"class C
{
/// <summary>
/// $$stuff
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// stuff
/// $$
/// </summary>
void M()
{
}
}";
VerifyOpenLineBelow(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineBelow3()
{
const string code =
@"/// <summary>
/// stuff
/// $$</summary>
";
const string expected =
@"/// <summary>
/// stuff
/// </summary>
/// $$
";
VerifyOpenLineBelow(code, expected);
}
[WorkItem(2090, "https://github.com/dotnet/roslyn/issues/2090")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void TestOpenLineBelow4_Tabs()
{
const string code =
@"class C
{
/// <summary>
/// $$stuff
/// </summary>
void M()
{
}
}";
const string expected =
@"class C
{
/// <summary>
/// stuff
/// $$
/// </summary>
void M()
{
}
}";
VerifyOpenLineBelow(code, expected, useTabs: true);
}
[WorkItem(468638, @"https://devdiv.visualstudio.com/DevDiv/NET%20Developer%20Experience%20IDE/_workitems/edit/468638")]
[WpfFact, Trait(Traits.Feature, Traits.Features.DocumentationComments)]
public void VerifyEnterWithTrimNewLineEditorConfigOption()
{
const string code =
@"/// <summary>
/// $$
/// </summary>
class C { }";
const string expected =
@"/// <summary>
///
/// $$
/// </summary>
class C { }";
try
{
VerifyPressingEnter(code, expected, useTabs: true, setOptionsOpt:
workspace =>
{
workspace.GetService<IEditorOptionsFactoryService>().GlobalOptions
.SetOptionValue(DefaultOptions.TrimTrailingWhiteSpaceOptionName, true);
});
}
finally
{
TestWorkspace.CreateCSharp("").GetService<IEditorOptionsFactoryService>().GlobalOptions
.SetOptionValue(DefaultOptions.TrimTrailingWhiteSpaceOptionName, false);
}
}
protected override char DocumentationCommentCharacter
{
get { return '/'; }
}
internal override ICommandHandler CreateCommandHandler(TestWorkspace workspace)
{
return workspace.ExportProvider.GetCommandHandler<DocumentationCommentCommandHandler>(PredefinedCommandHandlerNames.DocumentationComments, ContentTypeNames.CSharpContentType);
}
protected override TestWorkspace CreateTestWorkspace(string code)
=> TestWorkspace.CreateCSharp(code);
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/EditorFeatures/Core/Tagging/AsynchronousTaggerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
internal abstract class AsynchronousTaggerProvider<TTag> : AbstractAsynchronousTaggerProvider<TTag>, ITaggerProvider
where TTag : ITag
{
protected AsynchronousTaggerProvider(
IThreadingContext threadingContext,
IAsynchronousOperationListener asyncListener)
: base(threadingContext, asyncListener)
{
}
public ITagger<T> CreateTagger<T>(ITextBuffer subjectBuffer) where T : ITag
{
if (subjectBuffer == null)
throw new ArgumentNullException(nameof(subjectBuffer));
return this.CreateTaggerWorker<T>(null, subjectBuffer);
}
ITagger<T> ITaggerProvider.CreateTagger<T>(ITextBuffer buffer)
=> CreateTagger<T>(buffer);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
internal abstract class AsynchronousTaggerProvider<TTag> : AbstractAsynchronousTaggerProvider<TTag>, ITaggerProvider
where TTag : ITag
{
protected AsynchronousTaggerProvider(
IThreadingContext threadingContext,
IAsynchronousOperationListener asyncListener)
: base(threadingContext, asyncListener)
{
}
public ITagger<T> CreateTagger<T>(ITextBuffer subjectBuffer) where T : ITag
{
if (subjectBuffer == null)
throw new ArgumentNullException(nameof(subjectBuffer));
return this.CreateTaggerWorker<T>(null, subjectBuffer);
}
ITagger<T> ITaggerProvider.CreateTagger<T>(ITextBuffer buffer)
=> CreateTagger<T>(buffer);
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/VisualStudio/CSharp/Impl/Options/IntelliSenseOptionPage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
[Guid(Guids.CSharpOptionPageIntelliSenseIdString)]
internal class IntelliSenseOptionPage : AbstractOptionPage
{
protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore)
=> new IntelliSenseOptionPageControl(optionStore);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
[Guid(Guids.CSharpOptionPageIntelliSenseIdString)]
internal class IntelliSenseOptionPage : AbstractOptionPage
{
protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore)
=> new IntelliSenseOptionPageControl(optionStore);
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/VisualStudio/Core/Def/Implementation/PullMemberUp/MainDialog/PullMemberUpDialog.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.
#nullable disable
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.CodeAnalysis.PullMemberUp;
using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls;
using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.WarningDialog;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog
{
/// <summary>
/// Interaction logic for PullMemberUpDialog.xaml
/// </summary>
internal partial class PullMemberUpDialog : DialogWindow
{
public string OK => ServicesVSResources.OK;
public string Cancel => ServicesVSResources.Cancel;
public string PullMembersUpTitle => ServicesVSResources.Pull_Members_Up;
public string SelectMembers => ServicesVSResources.Select_members_colon;
public string SelectDestination => ServicesVSResources.Select_destination_colon;
public string Description => ServicesVSResources.Select_destination_and_members_to_pull_up;
public PullMemberUpDialogViewModel ViewModel { get; }
public MemberSelection MemberSelectionControl { get; }
public PullMemberUpDialog(PullMemberUpDialogViewModel pullMemberUpViewModel)
{
ViewModel = pullMemberUpViewModel;
DataContext = pullMemberUpViewModel;
MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel);
// Set focus to first tab control when the window is loaded
Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
InitializeComponent();
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
var options = ViewModel.CreatePullMemberUpOptions();
if (options.PullUpOperationNeedsToDoExtraChanges)
{
if (ShowWarningDialog(options))
{
DialogResult = true;
}
}
else
{
DialogResult = true;
}
}
private bool ShowWarningDialog(PullMembersUpOptions result)
{
var warningViewModel = new PullMemberUpWarningViewModel(result);
var warningDialog = new PullMemberUpWarningDialog(warningViewModel);
return warningDialog.ShowModal().GetValueOrDefault();
}
private void CancelButton_Click(object sender, RoutedEventArgs e) => DialogResult = false;
private void Destination_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (DestinationTreeView.SelectedItem is BaseTypeTreeNodeViewModel memberGraphNode)
{
ViewModel.SelectedDestination = memberGraphNode;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.CodeAnalysis.PullMemberUp;
using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls;
using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.WarningDialog;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog
{
/// <summary>
/// Interaction logic for PullMemberUpDialog.xaml
/// </summary>
internal partial class PullMemberUpDialog : DialogWindow
{
public string OK => ServicesVSResources.OK;
public string Cancel => ServicesVSResources.Cancel;
public string PullMembersUpTitle => ServicesVSResources.Pull_Members_Up;
public string SelectMembers => ServicesVSResources.Select_members_colon;
public string SelectDestination => ServicesVSResources.Select_destination_colon;
public string Description => ServicesVSResources.Select_destination_and_members_to_pull_up;
public PullMemberUpDialogViewModel ViewModel { get; }
public MemberSelection MemberSelectionControl { get; }
public PullMemberUpDialog(PullMemberUpDialogViewModel pullMemberUpViewModel)
{
ViewModel = pullMemberUpViewModel;
DataContext = pullMemberUpViewModel;
MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel);
// Set focus to first tab control when the window is loaded
Loaded += (s, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
InitializeComponent();
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
var options = ViewModel.CreatePullMemberUpOptions();
if (options.PullUpOperationNeedsToDoExtraChanges)
{
if (ShowWarningDialog(options))
{
DialogResult = true;
}
}
else
{
DialogResult = true;
}
}
private bool ShowWarningDialog(PullMembersUpOptions result)
{
var warningViewModel = new PullMemberUpWarningViewModel(result);
var warningDialog = new PullMemberUpWarningDialog(warningViewModel);
return warningDialog.ShowModal().GetValueOrDefault();
}
private void CancelButton_Click(object sender, RoutedEventArgs e) => DialogResult = false;
private void Destination_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (DestinationTreeView.SelectedItem is BaseTypeTreeNodeViewModel memberGraphNode)
{
ViewModel.SelectedDestination = memberGraphNode;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/Test/Utilities/CSharp/SyntaxTreeExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public static class SyntaxTreeExtensions
{
public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int offset, int length, string newText)
{
var oldFullText = syntaxTree.GetText();
var newFullText = oldFullText.WithChanges(new TextChange(new TextSpan(offset, length), newText));
return syntaxTree.WithChangedText(newFullText);
}
public static SyntaxTree WithReplaceFirst(this SyntaxTree syntaxTree, string oldText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(oldText, StringComparison.Ordinal);
int length = oldText.Length;
return WithReplace(syntaxTree, offset, length, newText);
}
public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int startIndex, string oldText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(oldText, startIndex, StringComparison.Ordinal); // Use an offset to find the first element to replace at
int length = oldText.Length;
return WithReplace(syntaxTree, offset, length, newText);
}
public static SyntaxTree WithInsertAt(this SyntaxTree syntaxTree, int offset, string newText)
{
return WithReplace(syntaxTree, offset, 0, newText);
}
public static SyntaxTree WithInsertBefore(this SyntaxTree syntaxTree, string existingText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(existingText, StringComparison.Ordinal);
return WithReplace(syntaxTree, offset, 0, newText);
}
public static SyntaxTree WithRemoveAt(this SyntaxTree syntaxTree, int offset, int length)
{
return WithReplace(syntaxTree, offset, length, string.Empty);
}
public static SyntaxTree WithRemoveFirst(this SyntaxTree syntaxTree, string oldText)
{
return WithReplaceFirst(syntaxTree, oldText, string.Empty);
}
internal static string Dump(this SyntaxNode node)
{
var visitor = new CSharpSyntaxPrinter();
visitor.Visit(node);
return visitor.Dump();
}
internal static string Dump(this SyntaxTree tree)
{
return tree.GetRoot().Dump();
}
private class CSharpSyntaxPrinter : CSharpSyntaxWalker
{
readonly PooledStringBuilder builder;
int indent = 0;
internal CSharpSyntaxPrinter()
{
builder = PooledStringBuilder.GetInstance();
}
internal string Dump()
{
return builder.ToStringAndFree();
}
public override void DefaultVisit(SyntaxNode node)
{
builder.Builder.Append(' ', repeatCount: indent);
builder.Builder.Append(node.Kind().ToString());
if (node.IsMissing)
{
builder.Builder.Append(" (missing)");
}
else if (node is IdentifierNameSyntax name)
{
builder.Builder.Append(" ");
builder.Builder.Append(name.ToString());
}
builder.Builder.AppendLine();
indent += 2;
base.DefaultVisit(node);
indent -= 2;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public static class SyntaxTreeExtensions
{
public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int offset, int length, string newText)
{
var oldFullText = syntaxTree.GetText();
var newFullText = oldFullText.WithChanges(new TextChange(new TextSpan(offset, length), newText));
return syntaxTree.WithChangedText(newFullText);
}
public static SyntaxTree WithReplaceFirst(this SyntaxTree syntaxTree, string oldText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(oldText, StringComparison.Ordinal);
int length = oldText.Length;
return WithReplace(syntaxTree, offset, length, newText);
}
public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int startIndex, string oldText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(oldText, startIndex, StringComparison.Ordinal); // Use an offset to find the first element to replace at
int length = oldText.Length;
return WithReplace(syntaxTree, offset, length, newText);
}
public static SyntaxTree WithInsertAt(this SyntaxTree syntaxTree, int offset, string newText)
{
return WithReplace(syntaxTree, offset, 0, newText);
}
public static SyntaxTree WithInsertBefore(this SyntaxTree syntaxTree, string existingText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(existingText, StringComparison.Ordinal);
return WithReplace(syntaxTree, offset, 0, newText);
}
public static SyntaxTree WithRemoveAt(this SyntaxTree syntaxTree, int offset, int length)
{
return WithReplace(syntaxTree, offset, length, string.Empty);
}
public static SyntaxTree WithRemoveFirst(this SyntaxTree syntaxTree, string oldText)
{
return WithReplaceFirst(syntaxTree, oldText, string.Empty);
}
internal static string Dump(this SyntaxNode node)
{
var visitor = new CSharpSyntaxPrinter();
visitor.Visit(node);
return visitor.Dump();
}
internal static string Dump(this SyntaxTree tree)
{
return tree.GetRoot().Dump();
}
private class CSharpSyntaxPrinter : CSharpSyntaxWalker
{
readonly PooledStringBuilder builder;
int indent = 0;
internal CSharpSyntaxPrinter()
{
builder = PooledStringBuilder.GetInstance();
}
internal string Dump()
{
return builder.ToStringAndFree();
}
public override void DefaultVisit(SyntaxNode node)
{
builder.Builder.Append(' ', repeatCount: indent);
builder.Builder.Append(node.Kind().ToString());
if (node.IsMissing)
{
builder.Builder.Append(" (missing)");
}
else if (node is IdentifierNameSyntax name)
{
builder.Builder.Append(" ");
builder.Builder.Append(name.ToString());
}
builder.Builder.AppendLine();
indent += 2;
base.DefaultVisit(node);
indent -= 2;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceField.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
protected override Task<Document> IntroduceFieldAsync(
SemanticDocument document,
ExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
CancellationToken cancellationToken)
{
var oldTypeDeclaration = expression.GetAncestorOrThis<TypeDeclarationSyntax>();
var oldType = oldTypeDeclaration != null
? document.SemanticModel.GetDeclaredSymbol(oldTypeDeclaration, cancellationToken) as INamedTypeSymbol
: document.SemanticModel.Compilation.ScriptClass;
var newNameToken = GenerateUniqueFieldName(document, expression, isConstant, cancellationToken);
var typeDisplayString = oldType.ToMinimalDisplayString(document.SemanticModel, expression.SpanStart);
var newQualifiedName = oldTypeDeclaration != null
? SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseName(typeDisplayString), SyntaxFactory.IdentifierName(newNameToken))
: (ExpressionSyntax)SyntaxFactory.IdentifierName(newNameToken);
newQualifiedName = newQualifiedName.WithAdditionalAnnotations(Simplifier.Annotation);
var newFieldDeclaration = SyntaxFactory.FieldDeclaration(
default,
MakeFieldModifiers(isConstant, inScript: oldType.IsScriptClass),
SyntaxFactory.VariableDeclaration(
GetTypeSymbol(document, expression, cancellationToken).GenerateTypeSyntax(),
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.VariableDeclarator(
newNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
null,
SyntaxFactory.EqualsValueClause(expression.WithoutTrivia()))))).WithAdditionalAnnotations(Formatter.Annotation);
if (oldTypeDeclaration != null)
{
var newTypeDeclaration = Rewrite(
document, expression, newQualifiedName, document, oldTypeDeclaration, allOccurrences, cancellationToken);
var insertionIndex = GetFieldInsertionIndex(isConstant, oldTypeDeclaration, newTypeDeclaration, cancellationToken);
var finalTypeDeclaration = InsertMember(newTypeDeclaration, newFieldDeclaration, insertionIndex);
var newRoot = document.Root.ReplaceNode(oldTypeDeclaration, finalTypeDeclaration);
return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
}
else
{
var oldCompilationUnit = (CompilationUnitSyntax)document.Root;
var newCompilationUnit = Rewrite(
document, expression, newQualifiedName, document, oldCompilationUnit, allOccurrences, cancellationToken);
var insertionIndex = isConstant ?
DetermineConstantInsertPosition(oldCompilationUnit.Members, newCompilationUnit.Members) :
DetermineFieldInsertPosition(oldCompilationUnit.Members, newCompilationUnit.Members);
var newRoot = newCompilationUnit.WithMembers(newCompilationUnit.Members.Insert(insertionIndex, newFieldDeclaration));
return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
}
}
protected override int DetermineConstantInsertPosition(TypeDeclarationSyntax oldType, TypeDeclarationSyntax newType)
=> DetermineConstantInsertPosition(oldType.Members, newType.Members);
protected static int DetermineConstantInsertPosition(
SyntaxList<MemberDeclarationSyntax> oldMembers,
SyntaxList<MemberDeclarationSyntax> newMembers)
{
// 1) Place the constant after the last constant.
//
// 2) If there is no constant, place it before the first field
//
// 3) If the first change is before either of those, then place before the first
// change
//
// 4) Otherwise, place it at the start.
var index = 0;
var lastConstantIndex = oldMembers.LastIndexOf(IsConstantField);
if (lastConstantIndex >= 0)
{
index = lastConstantIndex + 1;
}
else
{
var firstFieldIndex = oldMembers.IndexOf(member => member is FieldDeclarationSyntax);
if (firstFieldIndex >= 0)
{
index = firstFieldIndex;
}
}
var firstChangeIndex = DetermineFirstChange(oldMembers, newMembers);
if (firstChangeIndex >= 0)
{
index = Math.Min(index, firstChangeIndex);
}
return index;
}
protected override int DetermineFieldInsertPosition(TypeDeclarationSyntax oldType, TypeDeclarationSyntax newType)
=> DetermineFieldInsertPosition(oldType.Members, newType.Members);
protected static int DetermineFieldInsertPosition(
SyntaxList<MemberDeclarationSyntax> oldMembers,
SyntaxList<MemberDeclarationSyntax> newMembers)
{
// 1) Place the constant after the last field.
//
// 2) If there is no field, place it after the last constant
//
// 3) If the first change is before either of those, then place before the first
// change
//
// 4) Otherwise, place it at the start.
var index = 0;
var lastFieldIndex = oldMembers.LastIndexOf(member => member is FieldDeclarationSyntax);
if (lastFieldIndex >= 0)
{
index = lastFieldIndex + 1;
}
else
{
var lastConstantIndex = oldMembers.LastIndexOf(IsConstantField);
if (lastConstantIndex >= 0)
{
index = lastConstantIndex + 1;
}
}
var firstChangeIndex = DetermineFirstChange(oldMembers, newMembers);
if (firstChangeIndex >= 0)
{
index = Math.Min(index, firstChangeIndex);
}
return index;
}
private static bool IsConstantField(MemberDeclarationSyntax member)
=> member is FieldDeclarationSyntax field && field.Modifiers.Any(SyntaxKind.ConstKeyword);
protected static int DetermineFirstChange(SyntaxList<MemberDeclarationSyntax> oldMembers, SyntaxList<MemberDeclarationSyntax> newMembers)
{
for (var i = 0; i < oldMembers.Count; i++)
{
if (!SyntaxFactory.AreEquivalent(oldMembers[i], newMembers[i], topLevel: false))
{
return i;
}
}
return -1;
}
protected static TypeDeclarationSyntax InsertMember(
TypeDeclarationSyntax typeDeclaration,
MemberDeclarationSyntax memberDeclaration,
int index)
{
return typeDeclaration.WithMembers(
typeDeclaration.Members.Insert(index, memberDeclaration));
}
private static SyntaxTokenList MakeFieldModifiers(bool isConstant, bool inScript)
{
if (isConstant)
{
return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ConstKeyword));
}
else if (inScript)
{
return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
else
{
return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
protected override Task<Document> IntroduceFieldAsync(
SemanticDocument document,
ExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
CancellationToken cancellationToken)
{
var oldTypeDeclaration = expression.GetAncestorOrThis<TypeDeclarationSyntax>();
var oldType = oldTypeDeclaration != null
? document.SemanticModel.GetDeclaredSymbol(oldTypeDeclaration, cancellationToken) as INamedTypeSymbol
: document.SemanticModel.Compilation.ScriptClass;
var newNameToken = GenerateUniqueFieldName(document, expression, isConstant, cancellationToken);
var typeDisplayString = oldType.ToMinimalDisplayString(document.SemanticModel, expression.SpanStart);
var newQualifiedName = oldTypeDeclaration != null
? SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseName(typeDisplayString), SyntaxFactory.IdentifierName(newNameToken))
: (ExpressionSyntax)SyntaxFactory.IdentifierName(newNameToken);
newQualifiedName = newQualifiedName.WithAdditionalAnnotations(Simplifier.Annotation);
var newFieldDeclaration = SyntaxFactory.FieldDeclaration(
default,
MakeFieldModifiers(isConstant, inScript: oldType.IsScriptClass),
SyntaxFactory.VariableDeclaration(
GetTypeSymbol(document, expression, cancellationToken).GenerateTypeSyntax(),
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.VariableDeclarator(
newNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
null,
SyntaxFactory.EqualsValueClause(expression.WithoutTrivia()))))).WithAdditionalAnnotations(Formatter.Annotation);
if (oldTypeDeclaration != null)
{
var newTypeDeclaration = Rewrite(
document, expression, newQualifiedName, document, oldTypeDeclaration, allOccurrences, cancellationToken);
var insertionIndex = GetFieldInsertionIndex(isConstant, oldTypeDeclaration, newTypeDeclaration, cancellationToken);
var finalTypeDeclaration = InsertMember(newTypeDeclaration, newFieldDeclaration, insertionIndex);
var newRoot = document.Root.ReplaceNode(oldTypeDeclaration, finalTypeDeclaration);
return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
}
else
{
var oldCompilationUnit = (CompilationUnitSyntax)document.Root;
var newCompilationUnit = Rewrite(
document, expression, newQualifiedName, document, oldCompilationUnit, allOccurrences, cancellationToken);
var insertionIndex = isConstant ?
DetermineConstantInsertPosition(oldCompilationUnit.Members, newCompilationUnit.Members) :
DetermineFieldInsertPosition(oldCompilationUnit.Members, newCompilationUnit.Members);
var newRoot = newCompilationUnit.WithMembers(newCompilationUnit.Members.Insert(insertionIndex, newFieldDeclaration));
return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
}
}
protected override int DetermineConstantInsertPosition(TypeDeclarationSyntax oldType, TypeDeclarationSyntax newType)
=> DetermineConstantInsertPosition(oldType.Members, newType.Members);
protected static int DetermineConstantInsertPosition(
SyntaxList<MemberDeclarationSyntax> oldMembers,
SyntaxList<MemberDeclarationSyntax> newMembers)
{
// 1) Place the constant after the last constant.
//
// 2) If there is no constant, place it before the first field
//
// 3) If the first change is before either of those, then place before the first
// change
//
// 4) Otherwise, place it at the start.
var index = 0;
var lastConstantIndex = oldMembers.LastIndexOf(IsConstantField);
if (lastConstantIndex >= 0)
{
index = lastConstantIndex + 1;
}
else
{
var firstFieldIndex = oldMembers.IndexOf(member => member is FieldDeclarationSyntax);
if (firstFieldIndex >= 0)
{
index = firstFieldIndex;
}
}
var firstChangeIndex = DetermineFirstChange(oldMembers, newMembers);
if (firstChangeIndex >= 0)
{
index = Math.Min(index, firstChangeIndex);
}
return index;
}
protected override int DetermineFieldInsertPosition(TypeDeclarationSyntax oldType, TypeDeclarationSyntax newType)
=> DetermineFieldInsertPosition(oldType.Members, newType.Members);
protected static int DetermineFieldInsertPosition(
SyntaxList<MemberDeclarationSyntax> oldMembers,
SyntaxList<MemberDeclarationSyntax> newMembers)
{
// 1) Place the constant after the last field.
//
// 2) If there is no field, place it after the last constant
//
// 3) If the first change is before either of those, then place before the first
// change
//
// 4) Otherwise, place it at the start.
var index = 0;
var lastFieldIndex = oldMembers.LastIndexOf(member => member is FieldDeclarationSyntax);
if (lastFieldIndex >= 0)
{
index = lastFieldIndex + 1;
}
else
{
var lastConstantIndex = oldMembers.LastIndexOf(IsConstantField);
if (lastConstantIndex >= 0)
{
index = lastConstantIndex + 1;
}
}
var firstChangeIndex = DetermineFirstChange(oldMembers, newMembers);
if (firstChangeIndex >= 0)
{
index = Math.Min(index, firstChangeIndex);
}
return index;
}
private static bool IsConstantField(MemberDeclarationSyntax member)
=> member is FieldDeclarationSyntax field && field.Modifiers.Any(SyntaxKind.ConstKeyword);
protected static int DetermineFirstChange(SyntaxList<MemberDeclarationSyntax> oldMembers, SyntaxList<MemberDeclarationSyntax> newMembers)
{
for (var i = 0; i < oldMembers.Count; i++)
{
if (!SyntaxFactory.AreEquivalent(oldMembers[i], newMembers[i], topLevel: false))
{
return i;
}
}
return -1;
}
protected static TypeDeclarationSyntax InsertMember(
TypeDeclarationSyntax typeDeclaration,
MemberDeclarationSyntax memberDeclaration,
int index)
{
return typeDeclaration.WithMembers(
typeDeclaration.Members.Insert(index, memberDeclaration));
}
private static SyntaxTokenList MakeFieldModifiers(bool isConstant, bool inScript)
{
if (isConstant)
{
return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ConstKeyword));
}
else if (inScript)
{
return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
else
{
return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A helper class for synthesizing quantities of code.
/// </summary>
internal sealed class SyntheticBoundNodeFactory
{
/// <summary>
/// Thrown by the bound node factory when there is a failure to synthesize code.
/// An appropriate diagnostic is included that should be reported. Currently
/// the only diagnostic handled through this mechanism is a missing special/well-known
/// member.
/// </summary>
public class MissingPredefinedMember : Exception
{
public MissingPredefinedMember(Diagnostic error) : base(error.ToString())
{
this.Diagnostic = error;
}
public Diagnostic Diagnostic { get; }
}
public CSharpCompilation Compilation { get { return CompilationState.Compilation; } }
public SyntaxNode Syntax { get; set; }
public PEModuleBuilder? ModuleBuilderOpt { get { return CompilationState.ModuleBuilderOpt; } }
public BindingDiagnosticBag Diagnostics { get; }
public TypeCompilationState CompilationState { get; }
// Current enclosing type, or null if not available.
private NamedTypeSymbol? _currentType;
public NamedTypeSymbol? CurrentType
{
get { return _currentType; }
set
{
_currentType = value;
CheckCurrentType();
}
}
// current method, possibly a lambda or local function, or null if not available
private MethodSymbol? _currentFunction;
public MethodSymbol? CurrentFunction
{
get { return _currentFunction; }
set
{
_currentFunction = value;
if (value is { } &&
value.MethodKind != MethodKind.AnonymousFunction &&
value.MethodKind != MethodKind.LocalFunction)
{
_topLevelMethod = value;
_currentType = value.ContainingType;
}
CheckCurrentType();
}
}
// The nearest enclosing non-lambda method, or null if not available
private MethodSymbol? _topLevelMethod;
public MethodSymbol? TopLevelMethod
{
get { return _topLevelMethod; }
private set
{
_topLevelMethod = value;
CheckCurrentType();
}
}
/// <summary>
/// A binder suitable for performing overload resolution to synthesize a call to a helper method.
/// </summary>
private Binder? _binder;
internal BoundExpression MakeInvocationExpression(
BinderFlags flags,
SyntaxNode node,
BoundExpression receiver,
string methodName,
ImmutableArray<BoundExpression> args,
BindingDiagnosticBag diagnostics,
ImmutableArray<TypeSymbol> typeArgs = default(ImmutableArray<TypeSymbol>),
bool allowUnexpandedForm = true)
{
if (_binder is null || _binder.Flags != flags)
{
_binder = new SyntheticBinderImpl(this).WithFlags(flags);
}
return _binder.MakeInvocationExpression(
node,
receiver,
methodName,
args,
diagnostics,
typeArgs: typeArgs.IsDefault ? default(ImmutableArray<TypeWithAnnotations>) : typeArgs.SelectAsArray(t => TypeWithAnnotations.Create(t)),
allowFieldsAndProperties: false,
allowUnexpandedForm: allowUnexpandedForm);
}
/// <summary>
/// A binder used only for performing overload resolution of runtime helper methods.
/// </summary>
private sealed class SyntheticBinderImpl : BuckStopsHereBinder
{
private readonly SyntheticBoundNodeFactory _factory;
internal SyntheticBinderImpl(SyntheticBoundNodeFactory factory) : base(factory.Compilation)
{
_factory = factory;
}
internal override Symbol? ContainingMemberOrLambda { get { return _factory.CurrentFunction; } }
internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved)
{
return AccessCheck.IsSymbolAccessible(symbol, _factory.CurrentType, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved);
}
}
/// <summary>
/// Create a bound node factory. Note that the use of the factory to get special or well-known members
/// that do not exist will result in an exception of type <see cref="MissingPredefinedMember"/> being thrown.
/// </summary>
/// <param name="topLevelMethod">The top-level method that will contain the code</param>
/// <param name="node">The syntax node to which generated code should be attributed</param>
/// <param name="compilationState">The state of compilation of the enclosing type</param>
/// <param name="diagnostics">A bag where any diagnostics should be output</param>
public SyntheticBoundNodeFactory(MethodSymbol topLevelMethod, SyntaxNode node, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
: this(topLevelMethod, topLevelMethod.ContainingType, node, compilationState, diagnostics)
{
}
/// <param name="topLevelMethodOpt">The top-level method that will contain the code</param>
/// <param name="currentClassOpt">The enclosing class</param>
/// <param name="node">The syntax node to which generated code should be attributed</param>
/// <param name="compilationState">The state of compilation of the enclosing type</param>
/// <param name="diagnostics">A bag where any diagnostics should be output</param>
public SyntheticBoundNodeFactory(MethodSymbol? topLevelMethodOpt, NamedTypeSymbol? currentClassOpt, SyntaxNode node, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
Debug.Assert(node != null);
Debug.Assert(compilationState != null);
Debug.Assert(diagnostics != null);
this.CompilationState = compilationState;
this.CurrentType = currentClassOpt;
this.TopLevelMethod = topLevelMethodOpt;
this.CurrentFunction = topLevelMethodOpt;
this.Syntax = node;
this.Diagnostics = diagnostics;
}
[Conditional("DEBUG")]
private void CheckCurrentType()
{
if (CurrentType is { })
{
Debug.Assert(TopLevelMethod is null || TypeSymbol.Equals(TopLevelMethod.ContainingType, CurrentType, TypeCompareKind.ConsiderEverything2));
// In EE scenarios, lambdas and local functions are considered to be contained by the
// user-defined methods, rather than the EE-defined methods for which we are generating
// bound nodes. This is because the containing symbols are used to determine the type
// of the "this" parameter, which we need to be the user-defined types.
Debug.Assert(CurrentFunction is null ||
CurrentFunction.MethodKind == MethodKind.AnonymousFunction ||
CurrentFunction.MethodKind == MethodKind.LocalFunction ||
TypeSymbol.Equals(CurrentFunction.ContainingType, CurrentType, TypeCompareKind.ConsiderEverything2));
}
}
public void AddNestedType(NamedTypeSymbol nestedType)
{
// It is only valid to call this on a bound node factory with a module builder.
Debug.Assert(ModuleBuilderOpt is { });
ModuleBuilderOpt.AddSynthesizedDefinition(CurrentType, nestedType.GetCciAdapter());
}
public void OpenNestedType(NamedTypeSymbol nestedType)
{
// TODO: we used to have an invariant that a bound node factory was tied to a
// single enclosing class. This breaks that. It would be nice to reintroduce that
// invariant.
AddNestedType(nestedType);
CurrentFunction = null;
TopLevelMethod = null;
CurrentType = nestedType;
}
public BoundHoistedFieldAccess HoistedField(FieldSymbol field)
{
return new BoundHoistedFieldAccess(Syntax, field, field.Type);
}
public StateMachineFieldSymbol StateMachineField(TypeWithAnnotations type, string name, bool isPublic = false, bool isThis = false)
{
Debug.Assert(CurrentType is { });
var result = new StateMachineFieldSymbol(CurrentType, type, name, isPublic, isThis);
AddField(CurrentType, result);
return result;
}
public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, bool isPublic = false, bool isThis = false)
{
Debug.Assert(CurrentType is { });
var result = new StateMachineFieldSymbol(CurrentType, TypeWithAnnotations.Create(type), name, isPublic, isThis);
AddField(CurrentType, result);
return result;
}
public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, SynthesizedLocalKind synthesizedKind, int slotIndex)
{
Debug.Assert(CurrentType is { });
var result = new StateMachineFieldSymbol(CurrentType, type, name, synthesizedKind, slotIndex, isPublic: false);
AddField(CurrentType, result);
return result;
}
public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex)
{
Debug.Assert(CurrentType is { });
var result = new StateMachineFieldSymbol(CurrentType, type, name, slotDebugInfo, slotIndex, isPublic: false);
AddField(CurrentType, result);
return result;
}
public void AddField(NamedTypeSymbol containingType, FieldSymbol field)
{
// It is only valid to call this on a bound node factory with a module builder.
Debug.Assert(ModuleBuilderOpt is { });
ModuleBuilderOpt.AddSynthesizedDefinition(containingType, field.GetCciAdapter());
}
public GeneratedLabelSymbol GenerateLabel(string prefix)
{
return new GeneratedLabelSymbol(prefix);
}
public BoundThisReference This()
{
Debug.Assert(CurrentFunction is { IsStatic: false });
return new BoundThisReference(Syntax, CurrentFunction.ThisParameter.Type) { WasCompilerGenerated = true };
}
public BoundExpression This(LocalSymbol thisTempOpt)
{
return (thisTempOpt != null) ? Local(thisTempOpt) : (BoundExpression)This();
}
public BoundBaseReference Base(NamedTypeSymbol baseType)
{
Debug.Assert(CurrentFunction is { IsStatic: false });
return new BoundBaseReference(Syntax, baseType) { WasCompilerGenerated = true };
}
public BoundBadExpression BadExpression(TypeSymbol type)
{
return new BoundBadExpression(Syntax, LookupResultKind.Empty, ImmutableArray<Symbol?>.Empty, ImmutableArray<BoundExpression>.Empty, type, hasErrors: true);
}
public BoundParameter Parameter(ParameterSymbol p)
{
return new BoundParameter(Syntax, p, p.Type) { WasCompilerGenerated = true };
}
public BoundFieldAccess Field(BoundExpression? receiver, FieldSymbol f)
{
return new BoundFieldAccess(Syntax, receiver, f, ConstantValue.NotAvailable, LookupResultKind.Viable, f.Type) { WasCompilerGenerated = true };
}
public BoundFieldAccess InstanceField(FieldSymbol f)
{
return this.Field(this.This(), f);
}
public BoundExpression Property(WellKnownMember member)
{
return Property(null, member);
}
public BoundExpression Property(BoundExpression? receiverOpt, WellKnownMember member)
{
var propertySym = (PropertySymbol)WellKnownMember(member);
Debug.Assert(receiverOpt is null || receiverOpt.Type is { } &&
receiverOpt.Type.GetMembers(propertySym.Name).OfType<PropertySymbol>().Single() == propertySym);
Binder.ReportUseSite(propertySym, Diagnostics, Syntax);
return Property(receiverOpt, propertySym);
}
public BoundExpression Property(BoundExpression? receiverOpt, PropertySymbol property)
{
Debug.Assert((receiverOpt is null) == property.IsStatic);
return Call(receiverOpt, property.GetMethod); // TODO: should we use property.GetBaseProperty().GetMethod to ensure we generate a call to the overridden method?
}
public BoundExpression Indexer(BoundExpression? receiverOpt, PropertySymbol property, BoundExpression arg0)
{
Debug.Assert((receiverOpt is null) == property.IsStatic);
return Call(receiverOpt, property.GetMethod, arg0); // TODO: should we use property.GetBaseProperty().GetMethod to ensure we generate a call to the overridden method?
}
public NamedTypeSymbol SpecialType(SpecialType st)
{
NamedTypeSymbol specialType = Compilation.GetSpecialType(st);
Binder.ReportUseSite(specialType, Diagnostics, Syntax);
return specialType;
}
public ArrayTypeSymbol WellKnownArrayType(WellKnownType elementType)
{
return Compilation.CreateArrayTypeSymbol(WellKnownType(elementType));
}
public NamedTypeSymbol WellKnownType(WellKnownType wt)
{
NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType(wt);
Binder.ReportUseSite(wellKnownType, Diagnostics, Syntax);
return wellKnownType;
}
/// <summary>
/// Get the symbol for a well-known member. The use of this method to get a well-known member
/// that does not exist will result in an exception of type <see cref="MissingPredefinedMember"/> being thrown
/// containing an appropriate diagnostic for the caller to report.
/// </summary>
/// <param name="wm">The desired well-known member</param>
/// <param name="isOptional">If true, the method may return null for a missing member without an exception</param>
/// <returns>A symbol for the well-known member, or null if it is missing and <paramref name="isOptional"/> == true</returns>
public Symbol? WellKnownMember(WellKnownMember wm, bool isOptional)
{
Symbol wellKnownMember = Binder.GetWellKnownTypeMember(Compilation, wm, Diagnostics, syntax: Syntax, isOptional: true);
if (wellKnownMember is null && !isOptional)
{
RuntimeMembers.MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(wm);
var diagnostic = new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name), Syntax.Location);
throw new MissingPredefinedMember(diagnostic);
}
return wellKnownMember;
}
public Symbol WellKnownMember(WellKnownMember wm)
{
return WellKnownMember(wm, false)!;
}
public MethodSymbol? WellKnownMethod(WellKnownMember wm, bool isOptional)
{
return (MethodSymbol?)WellKnownMember(wm, isOptional);
}
public MethodSymbol WellKnownMethod(WellKnownMember wm)
{
return (MethodSymbol)WellKnownMember(wm, isOptional: false)!;
}
/// <summary>
/// Get the symbol for a special member. The use of this method to get a special member
/// that does not exist will result in an exception of type MissingPredefinedMember being thrown
/// containing an appropriate diagnostic for the caller to report.
/// </summary>
/// <param name="sm">The desired special member</param>
/// <returns>A symbol for the special member.</returns>
public Symbol SpecialMember(SpecialMember sm)
{
Symbol specialMember = Compilation.GetSpecialTypeMember(sm);
if (specialMember is null)
{
RuntimeMembers.MemberDescriptor memberDescriptor = SpecialMembers.GetDescriptor(sm);
var diagnostic = new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name), Syntax.Location);
throw new MissingPredefinedMember(diagnostic);
}
Binder.ReportUseSite(specialMember, Diagnostics, Syntax);
return specialMember;
}
public MethodSymbol SpecialMethod(SpecialMember sm)
{
return (MethodSymbol)SpecialMember(sm);
}
public PropertySymbol SpecialProperty(SpecialMember sm)
{
return (PropertySymbol)SpecialMember(sm);
}
public BoundExpressionStatement Assignment(BoundExpression left, BoundExpression right, bool isRef = false)
{
return ExpressionStatement(AssignmentExpression(left, right, isRef));
}
public BoundExpressionStatement ExpressionStatement(BoundExpression expr)
{
return new BoundExpressionStatement(Syntax, expr) { WasCompilerGenerated = true };
}
public BoundAssignmentOperator AssignmentExpression(BoundExpression left, BoundExpression right, bool isRef = false)
{
Debug.Assert(left.Type is { } && right.Type is { } &&
(left.Type.Equals(right.Type, TypeCompareKind.AllIgnoreOptions) ||
StackOptimizerPass1.IsFixedBufferAssignmentToRefLocal(left, right, isRef) ||
right.Type.IsErrorType() || left.Type.IsErrorType()));
return new BoundAssignmentOperator(Syntax, left, right, left.Type, isRef: isRef) { WasCompilerGenerated = true };
}
public BoundBlock Block()
{
return Block(ImmutableArray<BoundStatement>.Empty);
}
public BoundBlock Block(ImmutableArray<BoundStatement> statements)
{
return Block(ImmutableArray<LocalSymbol>.Empty, statements);
}
public BoundBlock Block(params BoundStatement[] statements)
{
return Block(ImmutableArray.Create(statements));
}
public BoundBlock Block(ImmutableArray<LocalSymbol> locals, params BoundStatement[] statements)
{
return Block(locals, ImmutableArray.Create(statements));
}
public BoundBlock Block(ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> statements)
{
return new BoundBlock(Syntax, locals, statements) { WasCompilerGenerated = true };
}
public BoundBlock Block(ImmutableArray<LocalSymbol> locals, ImmutableArray<LocalFunctionSymbol> localFunctions, params BoundStatement[] statements)
{
return Block(locals, localFunctions, ImmutableArray.Create(statements));
}
public BoundBlock Block(ImmutableArray<LocalSymbol> locals, ImmutableArray<LocalFunctionSymbol> localFunctions, ImmutableArray<BoundStatement> statements)
{
return new BoundBlock(Syntax, locals, localFunctions, statements) { WasCompilerGenerated = true };
}
public BoundExtractedFinallyBlock ExtractedFinallyBlock(BoundBlock finallyBlock)
{
return new BoundExtractedFinallyBlock(Syntax, finallyBlock) { WasCompilerGenerated = true };
}
public BoundStatementList StatementList()
{
return StatementList(ImmutableArray<BoundStatement>.Empty);
}
public BoundStatementList StatementList(ImmutableArray<BoundStatement> statements)
{
return new BoundStatementList(Syntax, statements) { WasCompilerGenerated = true };
}
public BoundStatementList StatementList(BoundStatement first, BoundStatement second)
{
return new BoundStatementList(Syntax, ImmutableArray.Create(first, second)) { WasCompilerGenerated = true };
}
public BoundReturnStatement Return(BoundExpression? expression = null)
{
Debug.Assert(CurrentFunction is { });
if (expression != null)
{
// If necessary, add a conversion on the return expression.
var useSiteInfo =
#if DEBUG
CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies;
#else
CompoundUseSiteInfo<AssemblySymbol>.Discarded;
#endif
var conversion = Compilation.Conversions.ClassifyConversionFromType(expression.Type, CurrentFunction.ReturnType, ref useSiteInfo);
Debug.Assert(useSiteInfo.Diagnostics.IsNullOrEmpty());
Debug.Assert(conversion.Kind != ConversionKind.NoConversion);
if (conversion.Kind != ConversionKind.Identity)
{
Debug.Assert(CurrentFunction.RefKind == RefKind.None);
expression = BoundConversion.Synthesized(Syntax, expression, conversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, CurrentFunction.ReturnType);
}
}
return new BoundReturnStatement(Syntax, CurrentFunction.RefKind, expression) { WasCompilerGenerated = true };
}
public void CloseMethod(BoundStatement body)
{
Debug.Assert(CurrentFunction is { });
if (body.Kind != BoundKind.Block)
{
body = Block(body);
}
CompilationState.AddSynthesizedMethod(CurrentFunction, body);
CurrentFunction = null;
}
public LocalSymbol SynthesizedLocal(
TypeSymbol type,
SyntaxNode? syntax = null,
bool isPinned = false,
RefKind refKind = RefKind.None,
SynthesizedLocalKind kind = SynthesizedLocalKind.LoweringTemp
#if DEBUG
,
[CallerLineNumber] int createdAtLineNumber = 0,
[CallerFilePath] string createdAtFilePath = ""
#endif
)
{
return new SynthesizedLocal(CurrentFunction, TypeWithAnnotations.Create(type), kind, syntax, isPinned, refKind
#if DEBUG
, createdAtLineNumber, createdAtFilePath
#endif
);
}
public LocalSymbol InterpolatedStringHandlerLocal(
TypeSymbol type,
uint valEscapeScope,
SyntaxNode syntax
#if DEBUG
,
[CallerLineNumber] int createdAtLineNumber = 0,
[CallerFilePath] string createdAtFilePath = ""
#endif
)
{
return new SynthesizedLocalWithValEscape(
CurrentFunction,
TypeWithAnnotations.Create(type),
SynthesizedLocalKind.LoweringTemp,
valEscapeScope,
syntax
#if DEBUG
, createdAtLineNumber: createdAtLineNumber, createdAtFilePath: createdAtFilePath
#endif
);
}
public ParameterSymbol SynthesizedParameter(TypeSymbol type, string name, MethodSymbol? container = null, int ordinal = 0)
{
return SynthesizedParameterSymbol.Create(container, TypeWithAnnotations.Create(type), ordinal, RefKind.None, name);
}
public BoundBinaryOperator Binary(BinaryOperatorKind kind, TypeSymbol type, BoundExpression left, BoundExpression right)
{
return new BoundBinaryOperator(this.Syntax, kind, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, left, right, type) { WasCompilerGenerated = true };
}
public BoundAsOperator As(BoundExpression operand, TypeSymbol type)
{
return new BoundAsOperator(this.Syntax, operand, Type(type), Conversion.ExplicitReference, type) { WasCompilerGenerated = true };
}
public BoundIsOperator Is(BoundExpression operand, TypeSymbol type)
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
// Because compiler-generated nodes are not lowered, this conversion is not used later in the compiler.
// But it is a required part of the `BoundIsOperator` node, so we compute a conversion here.
Conversion c = Compilation.Conversions.ClassifyBuiltInConversion(operand.Type, type, ref discardedUseSiteInfo);
return new BoundIsOperator(this.Syntax, operand, Type(type), c, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean)) { WasCompilerGenerated = true };
}
public BoundBinaryOperator LogicalAnd(BoundExpression left, BoundExpression right)
{
Debug.Assert(left.Type?.SpecialType == CodeAnalysis.SpecialType.System_Boolean);
Debug.Assert(right.Type?.SpecialType == CodeAnalysis.SpecialType.System_Boolean);
return Binary(BinaryOperatorKind.LogicalBoolAnd, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator LogicalOr(BoundExpression left, BoundExpression right)
{
Debug.Assert(left.Type?.SpecialType == CodeAnalysis.SpecialType.System_Boolean);
Debug.Assert(right.Type?.SpecialType == CodeAnalysis.SpecialType.System_Boolean);
return Binary(BinaryOperatorKind.LogicalBoolOr, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntEqual, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator ObjectEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.ObjectEqual, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator ObjectNotEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.ObjectNotEqual, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntNotEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntNotEqual, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntLessThan(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntLessThan, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntGreaterThanOrEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntGreaterThanOrEqual, SpecialType(CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntSubtract(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntSubtraction, SpecialType(CodeAnalysis.SpecialType.System_Int32), left, right);
}
public BoundLiteral Literal(int value)
{
return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32)) { WasCompilerGenerated = true };
}
public BoundLiteral Literal(uint value)
{
return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_UInt32)) { WasCompilerGenerated = true };
}
public BoundLiteral Literal(ConstantValue value, TypeSymbol type)
{
return new BoundLiteral(Syntax, value, type) { WasCompilerGenerated = true };
}
public BoundObjectCreationExpression New(NamedTypeSymbol type, params BoundExpression[] args)
{
var ctor = type.InstanceConstructors.Single(c => c.ParameterCount == args.Length);
return New(ctor, args);
}
public BoundObjectCreationExpression New(MethodSymbol ctor, params BoundExpression[] args)
=> New(ctor, args.ToImmutableArray());
public BoundObjectCreationExpression New(NamedTypeSymbol type, ImmutableArray<BoundExpression> args)
{
var ctor = type.InstanceConstructors.Single(c => c.ParameterCount == args.Length);
return New(ctor, args);
}
public BoundObjectCreationExpression New(MethodSymbol ctor, ImmutableArray<BoundExpression> args)
=> new BoundObjectCreationExpression(Syntax, ctor, args) { WasCompilerGenerated = true };
public BoundObjectCreationExpression New(WellKnownMember wm, ImmutableArray<BoundExpression> args)
{
var ctor = WellKnownMethod(wm);
return new BoundObjectCreationExpression(Syntax, ctor, args) { WasCompilerGenerated = true };
}
public BoundExpression MakeIsNotANumberTest(BoundExpression input)
{
switch (input.Type)
{
case { SpecialType: CodeAnalysis.SpecialType.System_Double }:
// produce double.IsNaN(input)
return StaticCall(CodeAnalysis.SpecialMember.System_Double__IsNaN, input);
case { SpecialType: CodeAnalysis.SpecialType.System_Single }:
// produce float.IsNaN(input)
return StaticCall(CodeAnalysis.SpecialMember.System_Single__IsNaN, input);
default:
throw ExceptionUtilities.UnexpectedValue(input.Type);
}
}
public BoundExpression InstanceCall(BoundExpression receiver, string name, BoundExpression arg)
{
return MakeInvocationExpression(BinderFlags.None, this.Syntax, receiver, name, ImmutableArray.Create(arg), this.Diagnostics);
}
public BoundExpression InstanceCall(BoundExpression receiver, string name)
{
return MakeInvocationExpression(BinderFlags.None, this.Syntax, receiver, name, ImmutableArray<BoundExpression>.Empty, this.Diagnostics);
}
public BoundExpression StaticCall(TypeSymbol receiver, string name, params BoundExpression[] args)
{
return MakeInvocationExpression(BinderFlags.None, this.Syntax, this.Type(receiver), name, args.ToImmutableArray(), this.Diagnostics);
}
public BoundExpression StaticCall(TypeSymbol receiver, string name, ImmutableArray<BoundExpression> args, bool allowUnexpandedForm)
{
return MakeInvocationExpression(BinderFlags.None, this.Syntax, this.Type(receiver), name, args, this.Diagnostics, allowUnexpandedForm: allowUnexpandedForm);
}
public BoundExpression StaticCall(BinderFlags flags, TypeSymbol receiver, string name, ImmutableArray<TypeSymbol> typeArgs, params BoundExpression[] args)
{
return MakeInvocationExpression(flags, this.Syntax, this.Type(receiver), name, args.ToImmutableArray(), this.Diagnostics, typeArgs);
}
public BoundExpression StaticCall(TypeSymbol receiver, MethodSymbol method, params BoundExpression[] args)
{
if (method is null)
{
return new BoundBadExpression(Syntax, default(LookupResultKind), ImmutableArray<Symbol?>.Empty, args.AsImmutable(), receiver);
}
return Call(null, method, args);
}
public BoundExpression StaticCall(MethodSymbol method, ImmutableArray<BoundExpression> args)
=> Call(null, method, args);
public BoundExpression StaticCall(WellKnownMember method, params BoundExpression[] args)
{
MethodSymbol methodSymbol = WellKnownMethod(method);
Binder.ReportUseSite(methodSymbol, Diagnostics, Syntax);
Debug.Assert(methodSymbol.IsStatic);
return Call(null, methodSymbol, args);
}
public BoundExpression StaticCall(SpecialMember method, params BoundExpression[] args)
{
MethodSymbol methodSymbol = SpecialMethod(method);
Binder.ReportUseSite(methodSymbol, Diagnostics, Syntax);
Debug.Assert(methodSymbol.IsStatic);
return Call(null, methodSymbol, args);
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method)
{
return Call(receiver, method, ImmutableArray<BoundExpression>.Empty);
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, BoundExpression arg0)
{
return Call(receiver, method, ImmutableArray.Create(arg0));
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, BoundExpression arg0, BoundExpression arg1)
{
return Call(receiver, method, ImmutableArray.Create(arg0, arg1));
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, params BoundExpression[] args)
{
return Call(receiver, method, ImmutableArray.Create<BoundExpression>(args));
}
public BoundCall Call(BoundExpression? receiver, WellKnownMember method, BoundExpression arg0)
=> Call(receiver, WellKnownMethod(method), ImmutableArray.Create(arg0));
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, ImmutableArray<BoundExpression> args)
{
Debug.Assert(method.ParameterCount == args.Length);
return new BoundCall(
Syntax, receiver, method, args,
argumentNamesOpt: default(ImmutableArray<String>), argumentRefKindsOpt: method.ParameterRefKinds, isDelegateCall: false, expanded: false,
invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable,
type: method.ReturnType, hasErrors: method.OriginalDefinition is ErrorMethodSymbol)
{ WasCompilerGenerated = true };
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, ImmutableArray<RefKind> refKinds, ImmutableArray<BoundExpression> args)
{
Debug.Assert(method.ParameterCount == args.Length);
return new BoundCall(
Syntax, receiver, method, args,
argumentNamesOpt: default(ImmutableArray<String>), argumentRefKindsOpt: refKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false,
argsToParamsOpt: ImmutableArray<int>.Empty, defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, type: method.ReturnType)
{ WasCompilerGenerated = true };
}
public BoundExpression Conditional(BoundExpression condition, BoundExpression consequence, BoundExpression alternative, TypeSymbol type)
{
return new BoundConditionalOperator(Syntax, false, condition, consequence, alternative, constantValueOpt: null, type, wasTargetTyped: false, type) { WasCompilerGenerated = true };
}
public BoundExpression ComplexConditionalReceiver(BoundExpression valueTypeReceiver, BoundExpression referenceTypeReceiver)
{
Debug.Assert(valueTypeReceiver.Type is { });
Debug.Assert(TypeSymbol.Equals(valueTypeReceiver.Type, referenceTypeReceiver.Type, TypeCompareKind.ConsiderEverything2));
return new BoundComplexConditionalReceiver(Syntax, valueTypeReceiver, referenceTypeReceiver, valueTypeReceiver.Type) { WasCompilerGenerated = true };
}
public BoundExpression Coalesce(BoundExpression left, BoundExpression right)
{
Debug.Assert(left.Type!.Equals(right.Type, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) || left.Type.IsErrorType());
Debug.Assert(left.Type.IsReferenceType);
return new BoundNullCoalescingOperator(Syntax, left, right, Conversion.Identity, BoundNullCoalescingOperatorResultKind.LeftType, left.Type) { WasCompilerGenerated = true };
}
public BoundStatement If(BoundExpression condition, BoundStatement thenClause, BoundStatement? elseClauseOpt = null)
{
return If(condition, ImmutableArray<LocalSymbol>.Empty, thenClause, elseClauseOpt);
}
public BoundStatement ConditionalGoto(BoundExpression condition, LabelSymbol label, bool jumpIfTrue)
{
return new BoundConditionalGoto(Syntax, condition, jumpIfTrue, label) { WasCompilerGenerated = true };
}
public BoundStatement If(BoundExpression condition, ImmutableArray<LocalSymbol> locals, BoundStatement thenClause, BoundStatement? elseClauseOpt = null)
{
// We translate
// if (condition) thenClause else elseClause
// as
// {
// ConditionalGoto(!condition) alternative
// thenClause
// goto afterif;
// alternative:
// elseClause
// afterif:
// }
Debug.Assert(thenClause != null);
var statements = ArrayBuilder<BoundStatement>.GetInstance();
var afterif = new GeneratedLabelSymbol("afterif");
if (elseClauseOpt != null)
{
var alt = new GeneratedLabelSymbol("alternative");
statements.Add(ConditionalGoto(condition, alt, false));
statements.Add(thenClause);
statements.Add(Goto(afterif));
if (!locals.IsDefaultOrEmpty)
{
var firstPart = this.Block(locals, statements.ToImmutable());
statements.Clear();
statements.Add(firstPart);
}
statements.Add(Label(alt));
statements.Add(elseClauseOpt);
}
else
{
statements.Add(ConditionalGoto(condition, afterif, false));
statements.Add(thenClause);
if (!locals.IsDefaultOrEmpty)
{
var firstPart = this.Block(locals, statements.ToImmutable());
statements.Clear();
statements.Add(firstPart);
}
}
statements.Add(Label(afterif));
return Block(statements.ToImmutableAndFree());
}
public BoundThrowStatement Throw(BoundExpression e)
{
return new BoundThrowStatement(Syntax, e) { WasCompilerGenerated = true };
}
public BoundLocal Local(LocalSymbol local)
{
return new BoundLocal(Syntax, local, null, local.Type) { WasCompilerGenerated = true };
}
public BoundExpression MakeSequence(LocalSymbol temp, params BoundExpression[] parts)
{
return MakeSequence(ImmutableArray.Create<LocalSymbol>(temp), parts);
}
public BoundExpression MakeSequence(params BoundExpression[] parts)
{
return MakeSequence(ImmutableArray<LocalSymbol>.Empty, parts);
}
public BoundExpression MakeSequence(ImmutableArray<LocalSymbol> locals, params BoundExpression[] parts)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance();
for (int i = 0; i < parts.Length - 1; i++)
{
var part = parts[i];
if (LocalRewriter.ReadIsSideeffecting(part))
{
builder.Add(parts[i]);
}
}
var lastExpression = parts[parts.Length - 1];
if (locals.IsDefaultOrEmpty && builder.Count == 0)
{
builder.Free();
return lastExpression;
}
return Sequence(locals, builder.ToImmutableAndFree(), lastExpression);
}
public BoundSequence Sequence(BoundExpression[] sideEffects, BoundExpression result, TypeSymbol? type = null)
{
Debug.Assert(result.Type is { });
var resultType = type ?? result.Type;
return new BoundSequence(Syntax, ImmutableArray<LocalSymbol>.Empty, sideEffects.AsImmutableOrNull(), result, resultType) { WasCompilerGenerated = true };
}
public BoundExpression Sequence(ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundExpression> sideEffects, BoundExpression result)
{
Debug.Assert(result.Type is { });
return
locals.IsDefaultOrEmpty && sideEffects.IsDefaultOrEmpty
? result
: new BoundSequence(Syntax, locals, sideEffects, result, result.Type) { WasCompilerGenerated = true };
}
public BoundSpillSequence SpillSequence(ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> sideEffects, BoundExpression result)
{
Debug.Assert(result.Type is { });
return new BoundSpillSequence(Syntax, locals, sideEffects, result, result.Type) { WasCompilerGenerated = true };
}
/// <summary>
/// An internal helper class for building a switch statement.
/// </summary>
internal class SyntheticSwitchSection
{
public readonly ImmutableArray<int> Values;
public readonly ImmutableArray<BoundStatement> Statements;
public SyntheticSwitchSection(ImmutableArray<int> Values, ImmutableArray<BoundStatement> Statements)
{
this.Values = Values;
this.Statements = Statements;
}
}
public SyntheticSwitchSection SwitchSection(int value, params BoundStatement[] statements)
{
return new SyntheticSwitchSection(ImmutableArray.Create(value), ImmutableArray.Create(statements));
}
public SyntheticSwitchSection SwitchSection(List<int> values, params BoundStatement[] statements)
{
return new SyntheticSwitchSection(ImmutableArray.CreateRange(values), ImmutableArray.Create(statements));
}
/// <summary>
/// Produce an int switch.
/// </summary>
public BoundStatement Switch(BoundExpression ex, ImmutableArray<SyntheticSwitchSection> sections)
{
Debug.Assert(ex.Type is { SpecialType: CodeAnalysis.SpecialType.System_Int32 });
if (sections.Length == 0)
{
return ExpressionStatement(ex);
}
CheckSwitchSections(sections);
GeneratedLabelSymbol breakLabel = new GeneratedLabelSymbol("break");
var caseBuilder = ArrayBuilder<(ConstantValue Value, LabelSymbol label)>.GetInstance();
var statements = ArrayBuilder<BoundStatement>.GetInstance();
statements.Add(null!); // placeholder at statements[0] for the dispatch
foreach (var section in sections)
{
LabelSymbol sectionLabel = new GeneratedLabelSymbol("case " + section.Values[0]);
statements.Add(Label(sectionLabel));
statements.AddRange(section.Statements);
foreach (var value in section.Values)
{
caseBuilder.Add((ConstantValue.Create(value), sectionLabel));
}
}
statements.Add(Label(breakLabel));
Debug.Assert(statements[0] is null);
statements[0] = new BoundSwitchDispatch(Syntax, ex, caseBuilder.ToImmutableAndFree(), breakLabel, null) { WasCompilerGenerated = true };
return Block(statements.ToImmutableAndFree());
}
/// <summary>
/// Check for (and assert that there are no) duplicate case labels in the switch.
/// </summary>
/// <param name="sections"></param>
[Conditional("DEBUG")]
private static void CheckSwitchSections(ImmutableArray<SyntheticSwitchSection> sections)
{
var labels = new HashSet<int>();
foreach (var s in sections)
{
foreach (var v2 in s.Values)
{
Debug.Assert(!labels.Contains(v2));
labels.Add(v2);
}
}
}
public BoundGotoStatement Goto(LabelSymbol label)
{
return new BoundGotoStatement(Syntax, label) { WasCompilerGenerated = true };
}
public BoundLabelStatement Label(LabelSymbol label)
{
return new BoundLabelStatement(Syntax, label) { WasCompilerGenerated = true };
}
public BoundLiteral Literal(Boolean value)
{
return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean)) { WasCompilerGenerated = true };
}
public BoundLiteral Literal(string? value)
{
var stringConst = ConstantValue.Create(value);
return StringLiteral(stringConst);
}
public BoundLiteral StringLiteral(ConstantValue stringConst)
{
Debug.Assert(stringConst.IsString || stringConst.IsNull);
return new BoundLiteral(Syntax, stringConst, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String)) { WasCompilerGenerated = true };
}
public BoundLiteral StringLiteral(String stringValue)
{
return StringLiteral(ConstantValue.Create(stringValue));
}
public BoundLiteral CharLiteral(ConstantValue charConst)
{
Debug.Assert(charConst.IsChar || charConst.IsDefaultValue);
return new BoundLiteral(Syntax, charConst, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Char)) { WasCompilerGenerated = true };
}
public BoundLiteral CharLiteral(Char charValue)
{
return CharLiteral(ConstantValue.Create(charValue));
}
public BoundArrayLength ArrayLength(BoundExpression array)
{
Debug.Assert(array.Type is { TypeKind: TypeKind.Array });
return new BoundArrayLength(Syntax, array, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32));
}
public BoundArrayAccess ArrayAccessFirstElement(BoundExpression array)
{
Debug.Assert(array.Type is { TypeKind: TypeKind.Array });
int rank = ((ArrayTypeSymbol)array.Type).Rank;
ImmutableArray<BoundExpression> firstElementIndices = ArrayBuilder<BoundExpression>.GetInstance(rank, Literal(0)).ToImmutableAndFree();
return ArrayAccess(array, firstElementIndices);
}
public BoundArrayAccess ArrayAccess(BoundExpression array, params BoundExpression[] indices)
{
return ArrayAccess(array, indices.AsImmutableOrNull());
}
public BoundArrayAccess ArrayAccess(BoundExpression array, ImmutableArray<BoundExpression> indices)
{
Debug.Assert(array.Type is { TypeKind: TypeKind.Array });
return new BoundArrayAccess(Syntax, array, indices, ((ArrayTypeSymbol)array.Type).ElementType);
}
public BoundStatement BaseInitialization()
{
// TODO: add diagnostics for when things fall apart
Debug.Assert(CurrentFunction is { });
NamedTypeSymbol baseType = CurrentFunction.ThisParameter.Type.BaseTypeNoUseSiteDiagnostics;
var ctor = baseType.InstanceConstructors.Single(c => c.ParameterCount == 0);
return new BoundExpressionStatement(Syntax, Call(Base(baseType), ctor)) { WasCompilerGenerated = true };
}
public BoundStatement SequencePoint(SyntaxNode syntax, BoundStatement statement)
{
return new BoundSequencePoint(syntax, statement);
}
public BoundStatement SequencePointWithSpan(CSharpSyntaxNode syntax, TextSpan span, BoundStatement statement)
{
return new BoundSequencePointWithSpan(syntax, statement, span);
}
public BoundStatement HiddenSequencePoint(BoundStatement? statementOpt = null)
{
return BoundSequencePoint.CreateHidden(statementOpt);
}
public BoundStatement ThrowNull()
{
return Throw(Null(Binder.GetWellKnownType(Compilation, Microsoft.CodeAnalysis.WellKnownType.System_Exception, Diagnostics, Syntax.Location)));
}
public BoundExpression ThrowExpression(BoundExpression thrown, TypeSymbol type)
{
return new BoundThrowExpression(thrown.Syntax, thrown, type) { WasCompilerGenerated = true };
}
public BoundExpression Null(TypeSymbol type)
{
return Null(type, Syntax);
}
public static BoundExpression Null(TypeSymbol type, SyntaxNode syntax)
{
Debug.Assert(type.CanBeAssignedNull());
BoundExpression nullLiteral = new BoundLiteral(syntax, ConstantValue.Null, type) { WasCompilerGenerated = true };
return type.IsPointerOrFunctionPointer()
? BoundConversion.SynthesizedNonUserDefined(syntax, nullLiteral, Conversion.NullToPointer, type)
: nullLiteral;
}
public BoundTypeExpression Type(TypeSymbol type)
{
return new BoundTypeExpression(Syntax, null, type) { WasCompilerGenerated = true };
}
public BoundExpression Typeof(WellKnownType type)
{
return Typeof(WellKnownType(type));
}
public BoundExpression Typeof(TypeSymbol type)
{
return new BoundTypeOfOperator(
Syntax,
Type(type),
WellKnownMethod(CodeAnalysis.WellKnownMember.System_Type__GetTypeFromHandle),
WellKnownType(CodeAnalysis.WellKnownType.System_Type))
{ WasCompilerGenerated = true };
}
public BoundExpression Typeof(TypeWithAnnotations type)
{
return Typeof(type.Type);
}
public ImmutableArray<BoundExpression> TypeOfs(ImmutableArray<TypeWithAnnotations> typeArguments)
{
return typeArguments.SelectAsArray(Typeof);
}
public BoundExpression TypeofDynamicOperationContextType()
{
Debug.Assert(this.CompilationState is { DynamicOperationContextType: { } });
return Typeof(this.CompilationState.DynamicOperationContextType);
}
public BoundExpression Sizeof(TypeSymbol type)
{
return new BoundSizeOfOperator(Syntax, Type(type), Binder.GetConstantSizeOf(type), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32)) { WasCompilerGenerated = true };
}
internal BoundExpression ConstructorInfo(MethodSymbol ctor)
{
return new BoundMethodInfo(
Syntax,
ctor,
GetMethodFromHandleMethod(ctor.ContainingType),
WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_ConstructorInfo))
{ WasCompilerGenerated = true };
}
public BoundExpression MethodDefIndex(MethodSymbol method)
{
return new BoundMethodDefIndex(
Syntax,
method,
SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
{ WasCompilerGenerated = true };
}
/// <summary>
/// Synthesizes an expression that evaluates to the current module's MVID.
/// </summary>
/// <returns></returns>
public BoundExpression ModuleVersionId()
{
return new BoundModuleVersionId(Syntax, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Guid)) { WasCompilerGenerated = true };
}
public BoundExpression ModuleVersionIdString()
{
return new BoundModuleVersionIdString(Syntax, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String)) { WasCompilerGenerated = true };
}
public BoundExpression InstrumentationPayloadRoot(int analysisKind, TypeSymbol payloadType)
{
return new BoundInstrumentationPayloadRoot(Syntax, analysisKind, payloadType) { WasCompilerGenerated = true };
}
public BoundExpression MaximumMethodDefIndex()
{
return new BoundMaximumMethodDefIndex(
Syntax,
SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
{ WasCompilerGenerated = true };
}
/// <summary>
/// Synthesizes an expression that evaluates to the index of a source document in the table of debug source documents.
/// </summary>
public BoundExpression SourceDocumentIndex(Cci.DebugSourceDocument document)
{
return new BoundSourceDocumentIndex(
Syntax,
document,
SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
{ WasCompilerGenerated = true };
}
public BoundExpression MethodInfo(MethodSymbol method)
{
// The least overridden virtual method is only called for value type receivers
// in special circumstances. These circumstances are exactly the checks performed by
// MayUseCallForStructMethod (which is also used by the emitter when determining
// whether or not to call a method with a value type receiver directly).
if (!method.ContainingType.IsValueType || !Microsoft.CodeAnalysis.CSharp.CodeGen.CodeGenerator.MayUseCallForStructMethod(method))
{
method = method.GetConstructedLeastOverriddenMethod(this.CompilationState.Type, requireSameReturnType: true);
}
return new BoundMethodInfo(
Syntax,
method,
GetMethodFromHandleMethod(method.ContainingType),
WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_MethodInfo))
{ WasCompilerGenerated = true };
}
public BoundExpression FieldInfo(FieldSymbol field)
{
return new BoundFieldInfo(
Syntax,
field,
GetFieldFromHandleMethod(field.ContainingType),
WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_FieldInfo))
{ WasCompilerGenerated = true };
}
private MethodSymbol GetMethodFromHandleMethod(NamedTypeSymbol methodContainer)
{
return WellKnownMethod(
(methodContainer.AllTypeArgumentCount() == 0 && !methodContainer.IsAnonymousType) ?
CodeAnalysis.WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle :
CodeAnalysis.WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle2);
}
private MethodSymbol GetFieldFromHandleMethod(NamedTypeSymbol fieldContainer)
{
return WellKnownMethod(
(fieldContainer.AllTypeArgumentCount() == 0) ?
CodeAnalysis.WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle :
CodeAnalysis.WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle2);
}
public BoundExpression Convert(TypeSymbol type, BoundExpression arg)
{
if (TypeSymbol.Equals(type, arg.Type, TypeCompareKind.ConsiderEverything2))
{
return arg;
}
var useSiteInfo =
#if DEBUG
CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies;
#else
CompoundUseSiteInfo<AssemblySymbol>.Discarded;
#endif
Conversion c = Compilation.Conversions.ClassifyConversionFromExpression(arg, type, ref useSiteInfo);
Debug.Assert(c.Exists);
Debug.Assert(useSiteInfo.Diagnostics.IsNullOrEmpty());
// If this happens, we should probably check if the method has ObsoleteAttribute.
Debug.Assert(c.Method is null, "Why are we synthesizing a user-defined conversion after initial binding?");
return Convert(type, arg, c);
}
public BoundExpression Convert(TypeSymbol type, BoundExpression arg, Conversion conversion, bool isChecked = false)
{
// NOTE: We can see user-defined conversions at this point because there are places in the bound tree where
// the binder stashes Conversion objects for later consumption (e.g. foreach, nullable, increment).
if (conversion.Method is { } && !TypeSymbol.Equals(conversion.Method.Parameters[0].Type, arg.Type, TypeCompareKind.ConsiderEverything2))
{
arg = Convert(conversion.Method.Parameters[0].Type, arg);
}
if (conversion.Kind == ConversionKind.ImplicitReference && arg.IsLiteralNull())
{
return Null(type);
}
Debug.Assert(arg.Type is { });
if (conversion.Kind == ConversionKind.ExplicitNullable &&
arg.Type.IsNullableType() &&
arg.Type.GetNullableUnderlyingType().Equals(type, TypeCompareKind.AllIgnoreOptions))
{
// A conversion to unbox a nullable value is produced when binding a pattern-matching
// operation from an operand of type T? to a pattern of type T.
return this.Call(arg, this.SpecialMethod(CodeAnalysis.SpecialMember.System_Nullable_T_get_Value).AsMember((NamedTypeSymbol)arg.Type));
}
return new BoundConversion(Syntax, arg, conversion, @checked: isChecked, explicitCastInCode: true, conversionGroupOpt: null, null, type) { WasCompilerGenerated = true };
}
public BoundExpression ArrayOrEmpty(TypeSymbol elementType, BoundExpression[] elements)
{
return ArrayOrEmpty(elementType, elements.AsImmutable());
}
/// <summary>
/// Helper that will use Array.Empty if available and elements have 0 length
/// NOTE: it is valid only if we know that the API that is being called will not
/// retain or use the array argument for any purpose (like locking or key in a hash table)
/// Typical example of valid use is Linq.Expressions factories - they do not make any
/// assumptions about array arguments and do not keep them or rely on their identity.
/// </summary>
public BoundExpression ArrayOrEmpty(TypeSymbol elementType, ImmutableArray<BoundExpression> elements)
{
if (elements.Length == 0)
{
MethodSymbol? arrayEmpty = WellKnownMethod(CodeAnalysis.WellKnownMember.System_Array__Empty, isOptional: true);
if (arrayEmpty is { })
{
arrayEmpty = arrayEmpty.Construct(ImmutableArray.Create(elementType));
return Call(null, arrayEmpty);
}
}
return Array(elementType, elements);
}
public BoundExpression Array(TypeSymbol elementType, ImmutableArray<BoundExpression> elements)
{
return new BoundArrayCreation(
Syntax,
ImmutableArray.Create<BoundExpression>(Literal(elements.Length)),
new BoundArrayInitialization(Syntax, elements) { WasCompilerGenerated = true },
Compilation.CreateArrayTypeSymbol(elementType));
}
public BoundExpression Array(TypeSymbol elementType, BoundExpression length)
{
return new BoundArrayCreation(
Syntax,
ImmutableArray.Create<BoundExpression>(length),
null,
Compilation.CreateArrayTypeSymbol(elementType))
{ WasCompilerGenerated = true };
}
internal BoundExpression Default(TypeSymbol type)
{
return Default(type, Syntax);
}
internal static BoundExpression Default(TypeSymbol type, SyntaxNode syntax)
{
return new BoundDefaultExpression(syntax, type) { WasCompilerGenerated = true };
}
internal BoundStatement Try(
BoundBlock tryBlock,
ImmutableArray<BoundCatchBlock> catchBlocks,
BoundBlock? finallyBlock = null,
LabelSymbol? finallyLabel = null)
{
return new BoundTryStatement(Syntax, tryBlock, catchBlocks, finallyBlock, finallyLabel) { WasCompilerGenerated = true };
}
internal ImmutableArray<BoundCatchBlock> CatchBlocks(
params BoundCatchBlock[] catchBlocks)
{
return catchBlocks.AsImmutableOrNull();
}
internal BoundCatchBlock Catch(
LocalSymbol local,
BoundBlock block)
{
var source = Local(local);
return new BoundCatchBlock(Syntax, ImmutableArray.Create(local), source, source.Type, exceptionFilterPrologueOpt: null, exceptionFilterOpt: null, body: block, isSynthesizedAsyncCatchAll: false);
}
internal BoundCatchBlock Catch(
BoundExpression source,
BoundBlock block)
{
return new BoundCatchBlock(Syntax, ImmutableArray<LocalSymbol>.Empty, source, source.Type, exceptionFilterPrologueOpt: null, exceptionFilterOpt: null, body: block, isSynthesizedAsyncCatchAll: false);
}
internal BoundTryStatement Fault(BoundBlock tryBlock, BoundBlock faultBlock)
{
return new BoundTryStatement(Syntax, tryBlock, ImmutableArray<BoundCatchBlock>.Empty, faultBlock, finallyLabelOpt: null, preferFaultHandler: true);
}
internal BoundExpression NullOrDefault(TypeSymbol typeSymbol)
{
return NullOrDefault(typeSymbol, this.Syntax);
}
internal static BoundExpression NullOrDefault(TypeSymbol typeSymbol, SyntaxNode syntax)
{
return typeSymbol.IsReferenceType ? Null(typeSymbol, syntax) : Default(typeSymbol, syntax);
}
internal BoundExpression Not(BoundExpression expression)
{
Debug.Assert(expression is { Type: { SpecialType: CodeAnalysis.SpecialType.System_Boolean } });
return new BoundUnaryOperator(expression.Syntax, UnaryOperatorKind.BoolLogicalNegation, expression, null, null, constrainedToTypeOpt: null, LookupResultKind.Viable, expression.Type);
}
/// <summary>
/// Takes an expression and returns the bound local expression "temp"
/// and the bound assignment expression "temp = expr".
/// </summary>
public BoundLocal StoreToTemp(
BoundExpression argument,
out BoundAssignmentOperator store,
RefKind refKind = RefKind.None,
SynthesizedLocalKind kind = SynthesizedLocalKind.LoweringTemp,
SyntaxNode? syntaxOpt = null
#if DEBUG
, [CallerLineNumber] int callerLineNumber = 0
, [CallerFilePath] string? callerFilePath = null
#endif
)
{
Debug.Assert(argument.Type is { });
MethodSymbol? containingMethod = this.CurrentFunction;
Debug.Assert(containingMethod is { });
switch (refKind)
{
case RefKind.Out:
refKind = RefKind.Ref;
break;
case RefKind.In:
if (!Binder.HasHome(argument,
Binder.AddressKind.ReadOnly,
containingMethod,
Compilation.IsPeVerifyCompatEnabled,
stackLocalsOpt: null))
{
// If there was an explicit 'in' on the argument then we should have verified
// earlier that we always have a home.
Debug.Assert(argument.GetRefKind() != RefKind.In);
refKind = RefKind.None;
}
break;
case RefKindExtensions.StrictIn:
case RefKind.None:
case RefKind.Ref:
break;
default:
throw ExceptionUtilities.UnexpectedValue(refKind);
}
var syntax = argument.Syntax;
var type = argument.Type;
var local = new BoundLocal(
syntax,
new SynthesizedLocal(
containingMethod,
TypeWithAnnotations.Create(type),
kind,
#if DEBUG
createdAtLineNumber: callerLineNumber,
createdAtFilePath: callerFilePath,
#endif
syntaxOpt: syntaxOpt ?? (kind.IsLongLived() ? syntax : null),
isPinned: false,
refKind: refKind),
null,
type);
store = new BoundAssignmentOperator(
syntax,
local,
argument,
refKind != RefKind.None,
type);
return local;
}
internal BoundStatement NoOp(NoOpStatementFlavor noOpStatementFlavor)
{
return new BoundNoOpStatement(Syntax, noOpStatementFlavor);
}
internal BoundLocal MakeTempForDiscard(BoundDiscardExpression node, ArrayBuilder<LocalSymbol> temps)
{
LocalSymbol temp;
BoundLocal result = MakeTempForDiscard(node, out temp);
temps.Add(temp);
return result;
}
internal BoundLocal MakeTempForDiscard(BoundDiscardExpression node, out LocalSymbol temp)
{
Debug.Assert(node.Type is { });
temp = new SynthesizedLocal(this.CurrentFunction, TypeWithAnnotations.Create(node.Type), SynthesizedLocalKind.LoweringTemp);
return new BoundLocal(node.Syntax, temp, constantValueOpt: null, type: node.Type) { WasCompilerGenerated = true };
}
internal ImmutableArray<BoundExpression> MakeTempsForDiscardArguments(ImmutableArray<BoundExpression> arguments, ArrayBuilder<LocalSymbol> builder)
{
var discardsPresent = arguments.Any(a => a.Kind == BoundKind.DiscardExpression);
if (discardsPresent)
{
arguments = arguments.SelectAsArray(
(arg, t) => arg.Kind == BoundKind.DiscardExpression ? t.factory.MakeTempForDiscard((BoundDiscardExpression)arg, t.builder) : arg,
(factory: this, builder: builder));
}
return arguments;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A helper class for synthesizing quantities of code.
/// </summary>
internal sealed class SyntheticBoundNodeFactory
{
/// <summary>
/// Thrown by the bound node factory when there is a failure to synthesize code.
/// An appropriate diagnostic is included that should be reported. Currently
/// the only diagnostic handled through this mechanism is a missing special/well-known
/// member.
/// </summary>
public class MissingPredefinedMember : Exception
{
public MissingPredefinedMember(Diagnostic error) : base(error.ToString())
{
this.Diagnostic = error;
}
public Diagnostic Diagnostic { get; }
}
public CSharpCompilation Compilation { get { return CompilationState.Compilation; } }
public SyntaxNode Syntax { get; set; }
public PEModuleBuilder? ModuleBuilderOpt { get { return CompilationState.ModuleBuilderOpt; } }
public BindingDiagnosticBag Diagnostics { get; }
public TypeCompilationState CompilationState { get; }
// Current enclosing type, or null if not available.
private NamedTypeSymbol? _currentType;
public NamedTypeSymbol? CurrentType
{
get { return _currentType; }
set
{
_currentType = value;
CheckCurrentType();
}
}
// current method, possibly a lambda or local function, or null if not available
private MethodSymbol? _currentFunction;
public MethodSymbol? CurrentFunction
{
get { return _currentFunction; }
set
{
_currentFunction = value;
if (value is { } &&
value.MethodKind != MethodKind.AnonymousFunction &&
value.MethodKind != MethodKind.LocalFunction)
{
_topLevelMethod = value;
_currentType = value.ContainingType;
}
CheckCurrentType();
}
}
// The nearest enclosing non-lambda method, or null if not available
private MethodSymbol? _topLevelMethod;
public MethodSymbol? TopLevelMethod
{
get { return _topLevelMethod; }
private set
{
_topLevelMethod = value;
CheckCurrentType();
}
}
/// <summary>
/// A binder suitable for performing overload resolution to synthesize a call to a helper method.
/// </summary>
private Binder? _binder;
internal BoundExpression MakeInvocationExpression(
BinderFlags flags,
SyntaxNode node,
BoundExpression receiver,
string methodName,
ImmutableArray<BoundExpression> args,
BindingDiagnosticBag diagnostics,
ImmutableArray<TypeSymbol> typeArgs = default(ImmutableArray<TypeSymbol>),
bool allowUnexpandedForm = true)
{
if (_binder is null || _binder.Flags != flags)
{
_binder = new SyntheticBinderImpl(this).WithFlags(flags);
}
return _binder.MakeInvocationExpression(
node,
receiver,
methodName,
args,
diagnostics,
typeArgs: typeArgs.IsDefault ? default(ImmutableArray<TypeWithAnnotations>) : typeArgs.SelectAsArray(t => TypeWithAnnotations.Create(t)),
allowFieldsAndProperties: false,
allowUnexpandedForm: allowUnexpandedForm);
}
/// <summary>
/// A binder used only for performing overload resolution of runtime helper methods.
/// </summary>
private sealed class SyntheticBinderImpl : BuckStopsHereBinder
{
private readonly SyntheticBoundNodeFactory _factory;
internal SyntheticBinderImpl(SyntheticBoundNodeFactory factory) : base(factory.Compilation)
{
_factory = factory;
}
internal override Symbol? ContainingMemberOrLambda { get { return _factory.CurrentFunction; } }
internal override bool IsAccessibleHelper(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved)
{
return AccessCheck.IsSymbolAccessible(symbol, _factory.CurrentType, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved);
}
}
/// <summary>
/// Create a bound node factory. Note that the use of the factory to get special or well-known members
/// that do not exist will result in an exception of type <see cref="MissingPredefinedMember"/> being thrown.
/// </summary>
/// <param name="topLevelMethod">The top-level method that will contain the code</param>
/// <param name="node">The syntax node to which generated code should be attributed</param>
/// <param name="compilationState">The state of compilation of the enclosing type</param>
/// <param name="diagnostics">A bag where any diagnostics should be output</param>
public SyntheticBoundNodeFactory(MethodSymbol topLevelMethod, SyntaxNode node, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
: this(topLevelMethod, topLevelMethod.ContainingType, node, compilationState, diagnostics)
{
}
/// <param name="topLevelMethodOpt">The top-level method that will contain the code</param>
/// <param name="currentClassOpt">The enclosing class</param>
/// <param name="node">The syntax node to which generated code should be attributed</param>
/// <param name="compilationState">The state of compilation of the enclosing type</param>
/// <param name="diagnostics">A bag where any diagnostics should be output</param>
public SyntheticBoundNodeFactory(MethodSymbol? topLevelMethodOpt, NamedTypeSymbol? currentClassOpt, SyntaxNode node, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
Debug.Assert(node != null);
Debug.Assert(compilationState != null);
Debug.Assert(diagnostics != null);
this.CompilationState = compilationState;
this.CurrentType = currentClassOpt;
this.TopLevelMethod = topLevelMethodOpt;
this.CurrentFunction = topLevelMethodOpt;
this.Syntax = node;
this.Diagnostics = diagnostics;
}
[Conditional("DEBUG")]
private void CheckCurrentType()
{
if (CurrentType is { })
{
Debug.Assert(TopLevelMethod is null || TypeSymbol.Equals(TopLevelMethod.ContainingType, CurrentType, TypeCompareKind.ConsiderEverything2));
// In EE scenarios, lambdas and local functions are considered to be contained by the
// user-defined methods, rather than the EE-defined methods for which we are generating
// bound nodes. This is because the containing symbols are used to determine the type
// of the "this" parameter, which we need to be the user-defined types.
Debug.Assert(CurrentFunction is null ||
CurrentFunction.MethodKind == MethodKind.AnonymousFunction ||
CurrentFunction.MethodKind == MethodKind.LocalFunction ||
TypeSymbol.Equals(CurrentFunction.ContainingType, CurrentType, TypeCompareKind.ConsiderEverything2));
}
}
public void AddNestedType(NamedTypeSymbol nestedType)
{
// It is only valid to call this on a bound node factory with a module builder.
Debug.Assert(ModuleBuilderOpt is { });
ModuleBuilderOpt.AddSynthesizedDefinition(CurrentType, nestedType.GetCciAdapter());
}
public void OpenNestedType(NamedTypeSymbol nestedType)
{
// TODO: we used to have an invariant that a bound node factory was tied to a
// single enclosing class. This breaks that. It would be nice to reintroduce that
// invariant.
AddNestedType(nestedType);
CurrentFunction = null;
TopLevelMethod = null;
CurrentType = nestedType;
}
public BoundHoistedFieldAccess HoistedField(FieldSymbol field)
{
return new BoundHoistedFieldAccess(Syntax, field, field.Type);
}
public StateMachineFieldSymbol StateMachineField(TypeWithAnnotations type, string name, bool isPublic = false, bool isThis = false)
{
Debug.Assert(CurrentType is { });
var result = new StateMachineFieldSymbol(CurrentType, type, name, isPublic, isThis);
AddField(CurrentType, result);
return result;
}
public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, bool isPublic = false, bool isThis = false)
{
Debug.Assert(CurrentType is { });
var result = new StateMachineFieldSymbol(CurrentType, TypeWithAnnotations.Create(type), name, isPublic, isThis);
AddField(CurrentType, result);
return result;
}
public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, SynthesizedLocalKind synthesizedKind, int slotIndex)
{
Debug.Assert(CurrentType is { });
var result = new StateMachineFieldSymbol(CurrentType, type, name, synthesizedKind, slotIndex, isPublic: false);
AddField(CurrentType, result);
return result;
}
public StateMachineFieldSymbol StateMachineField(TypeSymbol type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex)
{
Debug.Assert(CurrentType is { });
var result = new StateMachineFieldSymbol(CurrentType, type, name, slotDebugInfo, slotIndex, isPublic: false);
AddField(CurrentType, result);
return result;
}
public void AddField(NamedTypeSymbol containingType, FieldSymbol field)
{
// It is only valid to call this on a bound node factory with a module builder.
Debug.Assert(ModuleBuilderOpt is { });
ModuleBuilderOpt.AddSynthesizedDefinition(containingType, field.GetCciAdapter());
}
public GeneratedLabelSymbol GenerateLabel(string prefix)
{
return new GeneratedLabelSymbol(prefix);
}
public BoundThisReference This()
{
Debug.Assert(CurrentFunction is { IsStatic: false });
return new BoundThisReference(Syntax, CurrentFunction.ThisParameter.Type) { WasCompilerGenerated = true };
}
public BoundExpression This(LocalSymbol thisTempOpt)
{
return (thisTempOpt != null) ? Local(thisTempOpt) : (BoundExpression)This();
}
public BoundBaseReference Base(NamedTypeSymbol baseType)
{
Debug.Assert(CurrentFunction is { IsStatic: false });
return new BoundBaseReference(Syntax, baseType) { WasCompilerGenerated = true };
}
public BoundBadExpression BadExpression(TypeSymbol type)
{
return new BoundBadExpression(Syntax, LookupResultKind.Empty, ImmutableArray<Symbol?>.Empty, ImmutableArray<BoundExpression>.Empty, type, hasErrors: true);
}
public BoundParameter Parameter(ParameterSymbol p)
{
return new BoundParameter(Syntax, p, p.Type) { WasCompilerGenerated = true };
}
public BoundFieldAccess Field(BoundExpression? receiver, FieldSymbol f)
{
return new BoundFieldAccess(Syntax, receiver, f, ConstantValue.NotAvailable, LookupResultKind.Viable, f.Type) { WasCompilerGenerated = true };
}
public BoundFieldAccess InstanceField(FieldSymbol f)
{
return this.Field(this.This(), f);
}
public BoundExpression Property(WellKnownMember member)
{
return Property(null, member);
}
public BoundExpression Property(BoundExpression? receiverOpt, WellKnownMember member)
{
var propertySym = (PropertySymbol)WellKnownMember(member);
Debug.Assert(receiverOpt is null || receiverOpt.Type is { } &&
receiverOpt.Type.GetMembers(propertySym.Name).OfType<PropertySymbol>().Single() == propertySym);
Binder.ReportUseSite(propertySym, Diagnostics, Syntax);
return Property(receiverOpt, propertySym);
}
public BoundExpression Property(BoundExpression? receiverOpt, PropertySymbol property)
{
Debug.Assert((receiverOpt is null) == property.IsStatic);
return Call(receiverOpt, property.GetMethod); // TODO: should we use property.GetBaseProperty().GetMethod to ensure we generate a call to the overridden method?
}
public BoundExpression Indexer(BoundExpression? receiverOpt, PropertySymbol property, BoundExpression arg0)
{
Debug.Assert((receiverOpt is null) == property.IsStatic);
return Call(receiverOpt, property.GetMethod, arg0); // TODO: should we use property.GetBaseProperty().GetMethod to ensure we generate a call to the overridden method?
}
public NamedTypeSymbol SpecialType(SpecialType st)
{
NamedTypeSymbol specialType = Compilation.GetSpecialType(st);
Binder.ReportUseSite(specialType, Diagnostics, Syntax);
return specialType;
}
public ArrayTypeSymbol WellKnownArrayType(WellKnownType elementType)
{
return Compilation.CreateArrayTypeSymbol(WellKnownType(elementType));
}
public NamedTypeSymbol WellKnownType(WellKnownType wt)
{
NamedTypeSymbol wellKnownType = Compilation.GetWellKnownType(wt);
Binder.ReportUseSite(wellKnownType, Diagnostics, Syntax);
return wellKnownType;
}
/// <summary>
/// Get the symbol for a well-known member. The use of this method to get a well-known member
/// that does not exist will result in an exception of type <see cref="MissingPredefinedMember"/> being thrown
/// containing an appropriate diagnostic for the caller to report.
/// </summary>
/// <param name="wm">The desired well-known member</param>
/// <param name="isOptional">If true, the method may return null for a missing member without an exception</param>
/// <returns>A symbol for the well-known member, or null if it is missing and <paramref name="isOptional"/> == true</returns>
public Symbol? WellKnownMember(WellKnownMember wm, bool isOptional)
{
Symbol wellKnownMember = Binder.GetWellKnownTypeMember(Compilation, wm, Diagnostics, syntax: Syntax, isOptional: true);
if (wellKnownMember is null && !isOptional)
{
RuntimeMembers.MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(wm);
var diagnostic = new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name), Syntax.Location);
throw new MissingPredefinedMember(diagnostic);
}
return wellKnownMember;
}
public Symbol WellKnownMember(WellKnownMember wm)
{
return WellKnownMember(wm, false)!;
}
public MethodSymbol? WellKnownMethod(WellKnownMember wm, bool isOptional)
{
return (MethodSymbol?)WellKnownMember(wm, isOptional);
}
public MethodSymbol WellKnownMethod(WellKnownMember wm)
{
return (MethodSymbol)WellKnownMember(wm, isOptional: false)!;
}
/// <summary>
/// Get the symbol for a special member. The use of this method to get a special member
/// that does not exist will result in an exception of type MissingPredefinedMember being thrown
/// containing an appropriate diagnostic for the caller to report.
/// </summary>
/// <param name="sm">The desired special member</param>
/// <returns>A symbol for the special member.</returns>
public Symbol SpecialMember(SpecialMember sm)
{
Symbol specialMember = Compilation.GetSpecialTypeMember(sm);
if (specialMember is null)
{
RuntimeMembers.MemberDescriptor memberDescriptor = SpecialMembers.GetDescriptor(sm);
var diagnostic = new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name), Syntax.Location);
throw new MissingPredefinedMember(diagnostic);
}
Binder.ReportUseSite(specialMember, Diagnostics, Syntax);
return specialMember;
}
public MethodSymbol SpecialMethod(SpecialMember sm)
{
return (MethodSymbol)SpecialMember(sm);
}
public PropertySymbol SpecialProperty(SpecialMember sm)
{
return (PropertySymbol)SpecialMember(sm);
}
public BoundExpressionStatement Assignment(BoundExpression left, BoundExpression right, bool isRef = false)
{
return ExpressionStatement(AssignmentExpression(left, right, isRef));
}
public BoundExpressionStatement ExpressionStatement(BoundExpression expr)
{
return new BoundExpressionStatement(Syntax, expr) { WasCompilerGenerated = true };
}
public BoundAssignmentOperator AssignmentExpression(BoundExpression left, BoundExpression right, bool isRef = false)
{
Debug.Assert(left.Type is { } && right.Type is { } &&
(left.Type.Equals(right.Type, TypeCompareKind.AllIgnoreOptions) ||
StackOptimizerPass1.IsFixedBufferAssignmentToRefLocal(left, right, isRef) ||
right.Type.IsErrorType() || left.Type.IsErrorType()));
return new BoundAssignmentOperator(Syntax, left, right, left.Type, isRef: isRef) { WasCompilerGenerated = true };
}
public BoundBlock Block()
{
return Block(ImmutableArray<BoundStatement>.Empty);
}
public BoundBlock Block(ImmutableArray<BoundStatement> statements)
{
return Block(ImmutableArray<LocalSymbol>.Empty, statements);
}
public BoundBlock Block(params BoundStatement[] statements)
{
return Block(ImmutableArray.Create(statements));
}
public BoundBlock Block(ImmutableArray<LocalSymbol> locals, params BoundStatement[] statements)
{
return Block(locals, ImmutableArray.Create(statements));
}
public BoundBlock Block(ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> statements)
{
return new BoundBlock(Syntax, locals, statements) { WasCompilerGenerated = true };
}
public BoundBlock Block(ImmutableArray<LocalSymbol> locals, ImmutableArray<LocalFunctionSymbol> localFunctions, params BoundStatement[] statements)
{
return Block(locals, localFunctions, ImmutableArray.Create(statements));
}
public BoundBlock Block(ImmutableArray<LocalSymbol> locals, ImmutableArray<LocalFunctionSymbol> localFunctions, ImmutableArray<BoundStatement> statements)
{
return new BoundBlock(Syntax, locals, localFunctions, statements) { WasCompilerGenerated = true };
}
public BoundExtractedFinallyBlock ExtractedFinallyBlock(BoundBlock finallyBlock)
{
return new BoundExtractedFinallyBlock(Syntax, finallyBlock) { WasCompilerGenerated = true };
}
public BoundStatementList StatementList()
{
return StatementList(ImmutableArray<BoundStatement>.Empty);
}
public BoundStatementList StatementList(ImmutableArray<BoundStatement> statements)
{
return new BoundStatementList(Syntax, statements) { WasCompilerGenerated = true };
}
public BoundStatementList StatementList(BoundStatement first, BoundStatement second)
{
return new BoundStatementList(Syntax, ImmutableArray.Create(first, second)) { WasCompilerGenerated = true };
}
public BoundReturnStatement Return(BoundExpression? expression = null)
{
Debug.Assert(CurrentFunction is { });
if (expression != null)
{
// If necessary, add a conversion on the return expression.
var useSiteInfo =
#if DEBUG
CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies;
#else
CompoundUseSiteInfo<AssemblySymbol>.Discarded;
#endif
var conversion = Compilation.Conversions.ClassifyConversionFromType(expression.Type, CurrentFunction.ReturnType, ref useSiteInfo);
Debug.Assert(useSiteInfo.Diagnostics.IsNullOrEmpty());
Debug.Assert(conversion.Kind != ConversionKind.NoConversion);
if (conversion.Kind != ConversionKind.Identity)
{
Debug.Assert(CurrentFunction.RefKind == RefKind.None);
expression = BoundConversion.Synthesized(Syntax, expression, conversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, CurrentFunction.ReturnType);
}
}
return new BoundReturnStatement(Syntax, CurrentFunction.RefKind, expression) { WasCompilerGenerated = true };
}
public void CloseMethod(BoundStatement body)
{
Debug.Assert(CurrentFunction is { });
if (body.Kind != BoundKind.Block)
{
body = Block(body);
}
CompilationState.AddSynthesizedMethod(CurrentFunction, body);
CurrentFunction = null;
}
public LocalSymbol SynthesizedLocal(
TypeSymbol type,
SyntaxNode? syntax = null,
bool isPinned = false,
RefKind refKind = RefKind.None,
SynthesizedLocalKind kind = SynthesizedLocalKind.LoweringTemp
#if DEBUG
,
[CallerLineNumber] int createdAtLineNumber = 0,
[CallerFilePath] string createdAtFilePath = ""
#endif
)
{
return new SynthesizedLocal(CurrentFunction, TypeWithAnnotations.Create(type), kind, syntax, isPinned, refKind
#if DEBUG
, createdAtLineNumber, createdAtFilePath
#endif
);
}
public LocalSymbol InterpolatedStringHandlerLocal(
TypeSymbol type,
uint valEscapeScope,
SyntaxNode syntax
#if DEBUG
,
[CallerLineNumber] int createdAtLineNumber = 0,
[CallerFilePath] string createdAtFilePath = ""
#endif
)
{
return new SynthesizedLocalWithValEscape(
CurrentFunction,
TypeWithAnnotations.Create(type),
SynthesizedLocalKind.LoweringTemp,
valEscapeScope,
syntax
#if DEBUG
, createdAtLineNumber: createdAtLineNumber, createdAtFilePath: createdAtFilePath
#endif
);
}
public ParameterSymbol SynthesizedParameter(TypeSymbol type, string name, MethodSymbol? container = null, int ordinal = 0)
{
return SynthesizedParameterSymbol.Create(container, TypeWithAnnotations.Create(type), ordinal, RefKind.None, name);
}
public BoundBinaryOperator Binary(BinaryOperatorKind kind, TypeSymbol type, BoundExpression left, BoundExpression right)
{
return new BoundBinaryOperator(this.Syntax, kind, ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, left, right, type) { WasCompilerGenerated = true };
}
public BoundAsOperator As(BoundExpression operand, TypeSymbol type)
{
return new BoundAsOperator(this.Syntax, operand, Type(type), Conversion.ExplicitReference, type) { WasCompilerGenerated = true };
}
public BoundIsOperator Is(BoundExpression operand, TypeSymbol type)
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
// Because compiler-generated nodes are not lowered, this conversion is not used later in the compiler.
// But it is a required part of the `BoundIsOperator` node, so we compute a conversion here.
Conversion c = Compilation.Conversions.ClassifyBuiltInConversion(operand.Type, type, ref discardedUseSiteInfo);
return new BoundIsOperator(this.Syntax, operand, Type(type), c, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean)) { WasCompilerGenerated = true };
}
public BoundBinaryOperator LogicalAnd(BoundExpression left, BoundExpression right)
{
Debug.Assert(left.Type?.SpecialType == CodeAnalysis.SpecialType.System_Boolean);
Debug.Assert(right.Type?.SpecialType == CodeAnalysis.SpecialType.System_Boolean);
return Binary(BinaryOperatorKind.LogicalBoolAnd, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator LogicalOr(BoundExpression left, BoundExpression right)
{
Debug.Assert(left.Type?.SpecialType == CodeAnalysis.SpecialType.System_Boolean);
Debug.Assert(right.Type?.SpecialType == CodeAnalysis.SpecialType.System_Boolean);
return Binary(BinaryOperatorKind.LogicalBoolOr, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntEqual, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator ObjectEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.ObjectEqual, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator ObjectNotEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.ObjectNotEqual, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntNotEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntNotEqual, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntLessThan(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntLessThan, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntGreaterThanOrEqual(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntGreaterThanOrEqual, SpecialType(CodeAnalysis.SpecialType.System_Boolean), left, right);
}
public BoundBinaryOperator IntSubtract(BoundExpression left, BoundExpression right)
{
return Binary(BinaryOperatorKind.IntSubtraction, SpecialType(CodeAnalysis.SpecialType.System_Int32), left, right);
}
public BoundLiteral Literal(int value)
{
return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32)) { WasCompilerGenerated = true };
}
public BoundLiteral Literal(uint value)
{
return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_UInt32)) { WasCompilerGenerated = true };
}
public BoundLiteral Literal(ConstantValue value, TypeSymbol type)
{
return new BoundLiteral(Syntax, value, type) { WasCompilerGenerated = true };
}
public BoundObjectCreationExpression New(NamedTypeSymbol type, params BoundExpression[] args)
{
var ctor = type.InstanceConstructors.Single(c => c.ParameterCount == args.Length);
return New(ctor, args);
}
public BoundObjectCreationExpression New(MethodSymbol ctor, params BoundExpression[] args)
=> New(ctor, args.ToImmutableArray());
public BoundObjectCreationExpression New(NamedTypeSymbol type, ImmutableArray<BoundExpression> args)
{
var ctor = type.InstanceConstructors.Single(c => c.ParameterCount == args.Length);
return New(ctor, args);
}
public BoundObjectCreationExpression New(MethodSymbol ctor, ImmutableArray<BoundExpression> args)
=> new BoundObjectCreationExpression(Syntax, ctor, args) { WasCompilerGenerated = true };
public BoundObjectCreationExpression New(WellKnownMember wm, ImmutableArray<BoundExpression> args)
{
var ctor = WellKnownMethod(wm);
return new BoundObjectCreationExpression(Syntax, ctor, args) { WasCompilerGenerated = true };
}
public BoundExpression MakeIsNotANumberTest(BoundExpression input)
{
switch (input.Type)
{
case { SpecialType: CodeAnalysis.SpecialType.System_Double }:
// produce double.IsNaN(input)
return StaticCall(CodeAnalysis.SpecialMember.System_Double__IsNaN, input);
case { SpecialType: CodeAnalysis.SpecialType.System_Single }:
// produce float.IsNaN(input)
return StaticCall(CodeAnalysis.SpecialMember.System_Single__IsNaN, input);
default:
throw ExceptionUtilities.UnexpectedValue(input.Type);
}
}
public BoundExpression InstanceCall(BoundExpression receiver, string name, BoundExpression arg)
{
return MakeInvocationExpression(BinderFlags.None, this.Syntax, receiver, name, ImmutableArray.Create(arg), this.Diagnostics);
}
public BoundExpression InstanceCall(BoundExpression receiver, string name)
{
return MakeInvocationExpression(BinderFlags.None, this.Syntax, receiver, name, ImmutableArray<BoundExpression>.Empty, this.Diagnostics);
}
public BoundExpression StaticCall(TypeSymbol receiver, string name, params BoundExpression[] args)
{
return MakeInvocationExpression(BinderFlags.None, this.Syntax, this.Type(receiver), name, args.ToImmutableArray(), this.Diagnostics);
}
public BoundExpression StaticCall(TypeSymbol receiver, string name, ImmutableArray<BoundExpression> args, bool allowUnexpandedForm)
{
return MakeInvocationExpression(BinderFlags.None, this.Syntax, this.Type(receiver), name, args, this.Diagnostics, allowUnexpandedForm: allowUnexpandedForm);
}
public BoundExpression StaticCall(BinderFlags flags, TypeSymbol receiver, string name, ImmutableArray<TypeSymbol> typeArgs, params BoundExpression[] args)
{
return MakeInvocationExpression(flags, this.Syntax, this.Type(receiver), name, args.ToImmutableArray(), this.Diagnostics, typeArgs);
}
public BoundExpression StaticCall(TypeSymbol receiver, MethodSymbol method, params BoundExpression[] args)
{
if (method is null)
{
return new BoundBadExpression(Syntax, default(LookupResultKind), ImmutableArray<Symbol?>.Empty, args.AsImmutable(), receiver);
}
return Call(null, method, args);
}
public BoundExpression StaticCall(MethodSymbol method, ImmutableArray<BoundExpression> args)
=> Call(null, method, args);
public BoundExpression StaticCall(WellKnownMember method, params BoundExpression[] args)
{
MethodSymbol methodSymbol = WellKnownMethod(method);
Binder.ReportUseSite(methodSymbol, Diagnostics, Syntax);
Debug.Assert(methodSymbol.IsStatic);
return Call(null, methodSymbol, args);
}
public BoundExpression StaticCall(SpecialMember method, params BoundExpression[] args)
{
MethodSymbol methodSymbol = SpecialMethod(method);
Binder.ReportUseSite(methodSymbol, Diagnostics, Syntax);
Debug.Assert(methodSymbol.IsStatic);
return Call(null, methodSymbol, args);
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method)
{
return Call(receiver, method, ImmutableArray<BoundExpression>.Empty);
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, BoundExpression arg0)
{
return Call(receiver, method, ImmutableArray.Create(arg0));
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, BoundExpression arg0, BoundExpression arg1)
{
return Call(receiver, method, ImmutableArray.Create(arg0, arg1));
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, params BoundExpression[] args)
{
return Call(receiver, method, ImmutableArray.Create<BoundExpression>(args));
}
public BoundCall Call(BoundExpression? receiver, WellKnownMember method, BoundExpression arg0)
=> Call(receiver, WellKnownMethod(method), ImmutableArray.Create(arg0));
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, ImmutableArray<BoundExpression> args)
{
Debug.Assert(method.ParameterCount == args.Length);
return new BoundCall(
Syntax, receiver, method, args,
argumentNamesOpt: default(ImmutableArray<String>), argumentRefKindsOpt: method.ParameterRefKinds, isDelegateCall: false, expanded: false,
invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable,
type: method.ReturnType, hasErrors: method.OriginalDefinition is ErrorMethodSymbol)
{ WasCompilerGenerated = true };
}
public BoundCall Call(BoundExpression? receiver, MethodSymbol method, ImmutableArray<RefKind> refKinds, ImmutableArray<BoundExpression> args)
{
Debug.Assert(method.ParameterCount == args.Length);
return new BoundCall(
Syntax, receiver, method, args,
argumentNamesOpt: default(ImmutableArray<String>), argumentRefKindsOpt: refKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false,
argsToParamsOpt: ImmutableArray<int>.Empty, defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, type: method.ReturnType)
{ WasCompilerGenerated = true };
}
public BoundExpression Conditional(BoundExpression condition, BoundExpression consequence, BoundExpression alternative, TypeSymbol type)
{
return new BoundConditionalOperator(Syntax, false, condition, consequence, alternative, constantValueOpt: null, type, wasTargetTyped: false, type) { WasCompilerGenerated = true };
}
public BoundExpression ComplexConditionalReceiver(BoundExpression valueTypeReceiver, BoundExpression referenceTypeReceiver)
{
Debug.Assert(valueTypeReceiver.Type is { });
Debug.Assert(TypeSymbol.Equals(valueTypeReceiver.Type, referenceTypeReceiver.Type, TypeCompareKind.ConsiderEverything2));
return new BoundComplexConditionalReceiver(Syntax, valueTypeReceiver, referenceTypeReceiver, valueTypeReceiver.Type) { WasCompilerGenerated = true };
}
public BoundExpression Coalesce(BoundExpression left, BoundExpression right)
{
Debug.Assert(left.Type!.Equals(right.Type, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) || left.Type.IsErrorType());
Debug.Assert(left.Type.IsReferenceType);
return new BoundNullCoalescingOperator(Syntax, left, right, Conversion.Identity, BoundNullCoalescingOperatorResultKind.LeftType, left.Type) { WasCompilerGenerated = true };
}
public BoundStatement If(BoundExpression condition, BoundStatement thenClause, BoundStatement? elseClauseOpt = null)
{
return If(condition, ImmutableArray<LocalSymbol>.Empty, thenClause, elseClauseOpt);
}
public BoundStatement ConditionalGoto(BoundExpression condition, LabelSymbol label, bool jumpIfTrue)
{
return new BoundConditionalGoto(Syntax, condition, jumpIfTrue, label) { WasCompilerGenerated = true };
}
public BoundStatement If(BoundExpression condition, ImmutableArray<LocalSymbol> locals, BoundStatement thenClause, BoundStatement? elseClauseOpt = null)
{
// We translate
// if (condition) thenClause else elseClause
// as
// {
// ConditionalGoto(!condition) alternative
// thenClause
// goto afterif;
// alternative:
// elseClause
// afterif:
// }
Debug.Assert(thenClause != null);
var statements = ArrayBuilder<BoundStatement>.GetInstance();
var afterif = new GeneratedLabelSymbol("afterif");
if (elseClauseOpt != null)
{
var alt = new GeneratedLabelSymbol("alternative");
statements.Add(ConditionalGoto(condition, alt, false));
statements.Add(thenClause);
statements.Add(Goto(afterif));
if (!locals.IsDefaultOrEmpty)
{
var firstPart = this.Block(locals, statements.ToImmutable());
statements.Clear();
statements.Add(firstPart);
}
statements.Add(Label(alt));
statements.Add(elseClauseOpt);
}
else
{
statements.Add(ConditionalGoto(condition, afterif, false));
statements.Add(thenClause);
if (!locals.IsDefaultOrEmpty)
{
var firstPart = this.Block(locals, statements.ToImmutable());
statements.Clear();
statements.Add(firstPart);
}
}
statements.Add(Label(afterif));
return Block(statements.ToImmutableAndFree());
}
public BoundThrowStatement Throw(BoundExpression e)
{
return new BoundThrowStatement(Syntax, e) { WasCompilerGenerated = true };
}
public BoundLocal Local(LocalSymbol local)
{
return new BoundLocal(Syntax, local, null, local.Type) { WasCompilerGenerated = true };
}
public BoundExpression MakeSequence(LocalSymbol temp, params BoundExpression[] parts)
{
return MakeSequence(ImmutableArray.Create<LocalSymbol>(temp), parts);
}
public BoundExpression MakeSequence(params BoundExpression[] parts)
{
return MakeSequence(ImmutableArray<LocalSymbol>.Empty, parts);
}
public BoundExpression MakeSequence(ImmutableArray<LocalSymbol> locals, params BoundExpression[] parts)
{
var builder = ArrayBuilder<BoundExpression>.GetInstance();
for (int i = 0; i < parts.Length - 1; i++)
{
var part = parts[i];
if (LocalRewriter.ReadIsSideeffecting(part))
{
builder.Add(parts[i]);
}
}
var lastExpression = parts[parts.Length - 1];
if (locals.IsDefaultOrEmpty && builder.Count == 0)
{
builder.Free();
return lastExpression;
}
return Sequence(locals, builder.ToImmutableAndFree(), lastExpression);
}
public BoundSequence Sequence(BoundExpression[] sideEffects, BoundExpression result, TypeSymbol? type = null)
{
Debug.Assert(result.Type is { });
var resultType = type ?? result.Type;
return new BoundSequence(Syntax, ImmutableArray<LocalSymbol>.Empty, sideEffects.AsImmutableOrNull(), result, resultType) { WasCompilerGenerated = true };
}
public BoundExpression Sequence(ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundExpression> sideEffects, BoundExpression result)
{
Debug.Assert(result.Type is { });
return
locals.IsDefaultOrEmpty && sideEffects.IsDefaultOrEmpty
? result
: new BoundSequence(Syntax, locals, sideEffects, result, result.Type) { WasCompilerGenerated = true };
}
public BoundSpillSequence SpillSequence(ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> sideEffects, BoundExpression result)
{
Debug.Assert(result.Type is { });
return new BoundSpillSequence(Syntax, locals, sideEffects, result, result.Type) { WasCompilerGenerated = true };
}
/// <summary>
/// An internal helper class for building a switch statement.
/// </summary>
internal class SyntheticSwitchSection
{
public readonly ImmutableArray<int> Values;
public readonly ImmutableArray<BoundStatement> Statements;
public SyntheticSwitchSection(ImmutableArray<int> Values, ImmutableArray<BoundStatement> Statements)
{
this.Values = Values;
this.Statements = Statements;
}
}
public SyntheticSwitchSection SwitchSection(int value, params BoundStatement[] statements)
{
return new SyntheticSwitchSection(ImmutableArray.Create(value), ImmutableArray.Create(statements));
}
public SyntheticSwitchSection SwitchSection(List<int> values, params BoundStatement[] statements)
{
return new SyntheticSwitchSection(ImmutableArray.CreateRange(values), ImmutableArray.Create(statements));
}
/// <summary>
/// Produce an int switch.
/// </summary>
public BoundStatement Switch(BoundExpression ex, ImmutableArray<SyntheticSwitchSection> sections)
{
Debug.Assert(ex.Type is { SpecialType: CodeAnalysis.SpecialType.System_Int32 });
if (sections.Length == 0)
{
return ExpressionStatement(ex);
}
CheckSwitchSections(sections);
GeneratedLabelSymbol breakLabel = new GeneratedLabelSymbol("break");
var caseBuilder = ArrayBuilder<(ConstantValue Value, LabelSymbol label)>.GetInstance();
var statements = ArrayBuilder<BoundStatement>.GetInstance();
statements.Add(null!); // placeholder at statements[0] for the dispatch
foreach (var section in sections)
{
LabelSymbol sectionLabel = new GeneratedLabelSymbol("case " + section.Values[0]);
statements.Add(Label(sectionLabel));
statements.AddRange(section.Statements);
foreach (var value in section.Values)
{
caseBuilder.Add((ConstantValue.Create(value), sectionLabel));
}
}
statements.Add(Label(breakLabel));
Debug.Assert(statements[0] is null);
statements[0] = new BoundSwitchDispatch(Syntax, ex, caseBuilder.ToImmutableAndFree(), breakLabel, null) { WasCompilerGenerated = true };
return Block(statements.ToImmutableAndFree());
}
/// <summary>
/// Check for (and assert that there are no) duplicate case labels in the switch.
/// </summary>
/// <param name="sections"></param>
[Conditional("DEBUG")]
private static void CheckSwitchSections(ImmutableArray<SyntheticSwitchSection> sections)
{
var labels = new HashSet<int>();
foreach (var s in sections)
{
foreach (var v2 in s.Values)
{
Debug.Assert(!labels.Contains(v2));
labels.Add(v2);
}
}
}
public BoundGotoStatement Goto(LabelSymbol label)
{
return new BoundGotoStatement(Syntax, label) { WasCompilerGenerated = true };
}
public BoundLabelStatement Label(LabelSymbol label)
{
return new BoundLabelStatement(Syntax, label) { WasCompilerGenerated = true };
}
public BoundLiteral Literal(Boolean value)
{
return new BoundLiteral(Syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean)) { WasCompilerGenerated = true };
}
public BoundLiteral Literal(string? value)
{
var stringConst = ConstantValue.Create(value);
return StringLiteral(stringConst);
}
public BoundLiteral StringLiteral(ConstantValue stringConst)
{
Debug.Assert(stringConst.IsString || stringConst.IsNull);
return new BoundLiteral(Syntax, stringConst, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String)) { WasCompilerGenerated = true };
}
public BoundLiteral StringLiteral(String stringValue)
{
return StringLiteral(ConstantValue.Create(stringValue));
}
public BoundLiteral CharLiteral(ConstantValue charConst)
{
Debug.Assert(charConst.IsChar || charConst.IsDefaultValue);
return new BoundLiteral(Syntax, charConst, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Char)) { WasCompilerGenerated = true };
}
public BoundLiteral CharLiteral(Char charValue)
{
return CharLiteral(ConstantValue.Create(charValue));
}
public BoundArrayLength ArrayLength(BoundExpression array)
{
Debug.Assert(array.Type is { TypeKind: TypeKind.Array });
return new BoundArrayLength(Syntax, array, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32));
}
public BoundArrayAccess ArrayAccessFirstElement(BoundExpression array)
{
Debug.Assert(array.Type is { TypeKind: TypeKind.Array });
int rank = ((ArrayTypeSymbol)array.Type).Rank;
ImmutableArray<BoundExpression> firstElementIndices = ArrayBuilder<BoundExpression>.GetInstance(rank, Literal(0)).ToImmutableAndFree();
return ArrayAccess(array, firstElementIndices);
}
public BoundArrayAccess ArrayAccess(BoundExpression array, params BoundExpression[] indices)
{
return ArrayAccess(array, indices.AsImmutableOrNull());
}
public BoundArrayAccess ArrayAccess(BoundExpression array, ImmutableArray<BoundExpression> indices)
{
Debug.Assert(array.Type is { TypeKind: TypeKind.Array });
return new BoundArrayAccess(Syntax, array, indices, ((ArrayTypeSymbol)array.Type).ElementType);
}
public BoundStatement BaseInitialization()
{
// TODO: add diagnostics for when things fall apart
Debug.Assert(CurrentFunction is { });
NamedTypeSymbol baseType = CurrentFunction.ThisParameter.Type.BaseTypeNoUseSiteDiagnostics;
var ctor = baseType.InstanceConstructors.Single(c => c.ParameterCount == 0);
return new BoundExpressionStatement(Syntax, Call(Base(baseType), ctor)) { WasCompilerGenerated = true };
}
public BoundStatement SequencePoint(SyntaxNode syntax, BoundStatement statement)
{
return new BoundSequencePoint(syntax, statement);
}
public BoundStatement SequencePointWithSpan(CSharpSyntaxNode syntax, TextSpan span, BoundStatement statement)
{
return new BoundSequencePointWithSpan(syntax, statement, span);
}
public BoundStatement HiddenSequencePoint(BoundStatement? statementOpt = null)
{
return BoundSequencePoint.CreateHidden(statementOpt);
}
public BoundStatement ThrowNull()
{
return Throw(Null(Binder.GetWellKnownType(Compilation, Microsoft.CodeAnalysis.WellKnownType.System_Exception, Diagnostics, Syntax.Location)));
}
public BoundExpression ThrowExpression(BoundExpression thrown, TypeSymbol type)
{
return new BoundThrowExpression(thrown.Syntax, thrown, type) { WasCompilerGenerated = true };
}
public BoundExpression Null(TypeSymbol type)
{
return Null(type, Syntax);
}
public static BoundExpression Null(TypeSymbol type, SyntaxNode syntax)
{
Debug.Assert(type.CanBeAssignedNull());
BoundExpression nullLiteral = new BoundLiteral(syntax, ConstantValue.Null, type) { WasCompilerGenerated = true };
return type.IsPointerOrFunctionPointer()
? BoundConversion.SynthesizedNonUserDefined(syntax, nullLiteral, Conversion.NullToPointer, type)
: nullLiteral;
}
public BoundTypeExpression Type(TypeSymbol type)
{
return new BoundTypeExpression(Syntax, null, type) { WasCompilerGenerated = true };
}
public BoundExpression Typeof(WellKnownType type)
{
return Typeof(WellKnownType(type));
}
public BoundExpression Typeof(TypeSymbol type)
{
return new BoundTypeOfOperator(
Syntax,
Type(type),
WellKnownMethod(CodeAnalysis.WellKnownMember.System_Type__GetTypeFromHandle),
WellKnownType(CodeAnalysis.WellKnownType.System_Type))
{ WasCompilerGenerated = true };
}
public BoundExpression Typeof(TypeWithAnnotations type)
{
return Typeof(type.Type);
}
public ImmutableArray<BoundExpression> TypeOfs(ImmutableArray<TypeWithAnnotations> typeArguments)
{
return typeArguments.SelectAsArray(Typeof);
}
public BoundExpression TypeofDynamicOperationContextType()
{
Debug.Assert(this.CompilationState is { DynamicOperationContextType: { } });
return Typeof(this.CompilationState.DynamicOperationContextType);
}
public BoundExpression Sizeof(TypeSymbol type)
{
return new BoundSizeOfOperator(Syntax, Type(type), Binder.GetConstantSizeOf(type), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32)) { WasCompilerGenerated = true };
}
internal BoundExpression ConstructorInfo(MethodSymbol ctor)
{
return new BoundMethodInfo(
Syntax,
ctor,
GetMethodFromHandleMethod(ctor.ContainingType),
WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_ConstructorInfo))
{ WasCompilerGenerated = true };
}
public BoundExpression MethodDefIndex(MethodSymbol method)
{
return new BoundMethodDefIndex(
Syntax,
method,
SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
{ WasCompilerGenerated = true };
}
/// <summary>
/// Synthesizes an expression that evaluates to the current module's MVID.
/// </summary>
/// <returns></returns>
public BoundExpression ModuleVersionId()
{
return new BoundModuleVersionId(Syntax, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Guid)) { WasCompilerGenerated = true };
}
public BoundExpression ModuleVersionIdString()
{
return new BoundModuleVersionIdString(Syntax, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String)) { WasCompilerGenerated = true };
}
public BoundExpression InstrumentationPayloadRoot(int analysisKind, TypeSymbol payloadType)
{
return new BoundInstrumentationPayloadRoot(Syntax, analysisKind, payloadType) { WasCompilerGenerated = true };
}
public BoundExpression MaximumMethodDefIndex()
{
return new BoundMaximumMethodDefIndex(
Syntax,
SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
{ WasCompilerGenerated = true };
}
/// <summary>
/// Synthesizes an expression that evaluates to the index of a source document in the table of debug source documents.
/// </summary>
public BoundExpression SourceDocumentIndex(Cci.DebugSourceDocument document)
{
return new BoundSourceDocumentIndex(
Syntax,
document,
SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
{ WasCompilerGenerated = true };
}
public BoundExpression MethodInfo(MethodSymbol method)
{
// The least overridden virtual method is only called for value type receivers
// in special circumstances. These circumstances are exactly the checks performed by
// MayUseCallForStructMethod (which is also used by the emitter when determining
// whether or not to call a method with a value type receiver directly).
if (!method.ContainingType.IsValueType || !Microsoft.CodeAnalysis.CSharp.CodeGen.CodeGenerator.MayUseCallForStructMethod(method))
{
method = method.GetConstructedLeastOverriddenMethod(this.CompilationState.Type, requireSameReturnType: true);
}
return new BoundMethodInfo(
Syntax,
method,
GetMethodFromHandleMethod(method.ContainingType),
WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_MethodInfo))
{ WasCompilerGenerated = true };
}
public BoundExpression FieldInfo(FieldSymbol field)
{
return new BoundFieldInfo(
Syntax,
field,
GetFieldFromHandleMethod(field.ContainingType),
WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_FieldInfo))
{ WasCompilerGenerated = true };
}
private MethodSymbol GetMethodFromHandleMethod(NamedTypeSymbol methodContainer)
{
return WellKnownMethod(
(methodContainer.AllTypeArgumentCount() == 0 && !methodContainer.IsAnonymousType) ?
CodeAnalysis.WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle :
CodeAnalysis.WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle2);
}
private MethodSymbol GetFieldFromHandleMethod(NamedTypeSymbol fieldContainer)
{
return WellKnownMethod(
(fieldContainer.AllTypeArgumentCount() == 0) ?
CodeAnalysis.WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle :
CodeAnalysis.WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle2);
}
public BoundExpression Convert(TypeSymbol type, BoundExpression arg)
{
if (TypeSymbol.Equals(type, arg.Type, TypeCompareKind.ConsiderEverything2))
{
return arg;
}
var useSiteInfo =
#if DEBUG
CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies;
#else
CompoundUseSiteInfo<AssemblySymbol>.Discarded;
#endif
Conversion c = Compilation.Conversions.ClassifyConversionFromExpression(arg, type, ref useSiteInfo);
Debug.Assert(c.Exists);
Debug.Assert(useSiteInfo.Diagnostics.IsNullOrEmpty());
// If this happens, we should probably check if the method has ObsoleteAttribute.
Debug.Assert(c.Method is null, "Why are we synthesizing a user-defined conversion after initial binding?");
return Convert(type, arg, c);
}
public BoundExpression Convert(TypeSymbol type, BoundExpression arg, Conversion conversion, bool isChecked = false)
{
// NOTE: We can see user-defined conversions at this point because there are places in the bound tree where
// the binder stashes Conversion objects for later consumption (e.g. foreach, nullable, increment).
if (conversion.Method is { } && !TypeSymbol.Equals(conversion.Method.Parameters[0].Type, arg.Type, TypeCompareKind.ConsiderEverything2))
{
arg = Convert(conversion.Method.Parameters[0].Type, arg);
}
if (conversion.Kind == ConversionKind.ImplicitReference && arg.IsLiteralNull())
{
return Null(type);
}
Debug.Assert(arg.Type is { });
if (conversion.Kind == ConversionKind.ExplicitNullable &&
arg.Type.IsNullableType() &&
arg.Type.GetNullableUnderlyingType().Equals(type, TypeCompareKind.AllIgnoreOptions))
{
// A conversion to unbox a nullable value is produced when binding a pattern-matching
// operation from an operand of type T? to a pattern of type T.
return this.Call(arg, this.SpecialMethod(CodeAnalysis.SpecialMember.System_Nullable_T_get_Value).AsMember((NamedTypeSymbol)arg.Type));
}
return new BoundConversion(Syntax, arg, conversion, @checked: isChecked, explicitCastInCode: true, conversionGroupOpt: null, null, type) { WasCompilerGenerated = true };
}
public BoundExpression ArrayOrEmpty(TypeSymbol elementType, BoundExpression[] elements)
{
return ArrayOrEmpty(elementType, elements.AsImmutable());
}
/// <summary>
/// Helper that will use Array.Empty if available and elements have 0 length
/// NOTE: it is valid only if we know that the API that is being called will not
/// retain or use the array argument for any purpose (like locking or key in a hash table)
/// Typical example of valid use is Linq.Expressions factories - they do not make any
/// assumptions about array arguments and do not keep them or rely on their identity.
/// </summary>
public BoundExpression ArrayOrEmpty(TypeSymbol elementType, ImmutableArray<BoundExpression> elements)
{
if (elements.Length == 0)
{
MethodSymbol? arrayEmpty = WellKnownMethod(CodeAnalysis.WellKnownMember.System_Array__Empty, isOptional: true);
if (arrayEmpty is { })
{
arrayEmpty = arrayEmpty.Construct(ImmutableArray.Create(elementType));
return Call(null, arrayEmpty);
}
}
return Array(elementType, elements);
}
public BoundExpression Array(TypeSymbol elementType, ImmutableArray<BoundExpression> elements)
{
return new BoundArrayCreation(
Syntax,
ImmutableArray.Create<BoundExpression>(Literal(elements.Length)),
new BoundArrayInitialization(Syntax, elements) { WasCompilerGenerated = true },
Compilation.CreateArrayTypeSymbol(elementType));
}
public BoundExpression Array(TypeSymbol elementType, BoundExpression length)
{
return new BoundArrayCreation(
Syntax,
ImmutableArray.Create<BoundExpression>(length),
null,
Compilation.CreateArrayTypeSymbol(elementType))
{ WasCompilerGenerated = true };
}
internal BoundExpression Default(TypeSymbol type)
{
return Default(type, Syntax);
}
internal static BoundExpression Default(TypeSymbol type, SyntaxNode syntax)
{
return new BoundDefaultExpression(syntax, type) { WasCompilerGenerated = true };
}
internal BoundStatement Try(
BoundBlock tryBlock,
ImmutableArray<BoundCatchBlock> catchBlocks,
BoundBlock? finallyBlock = null,
LabelSymbol? finallyLabel = null)
{
return new BoundTryStatement(Syntax, tryBlock, catchBlocks, finallyBlock, finallyLabel) { WasCompilerGenerated = true };
}
internal ImmutableArray<BoundCatchBlock> CatchBlocks(
params BoundCatchBlock[] catchBlocks)
{
return catchBlocks.AsImmutableOrNull();
}
internal BoundCatchBlock Catch(
LocalSymbol local,
BoundBlock block)
{
var source = Local(local);
return new BoundCatchBlock(Syntax, ImmutableArray.Create(local), source, source.Type, exceptionFilterPrologueOpt: null, exceptionFilterOpt: null, body: block, isSynthesizedAsyncCatchAll: false);
}
internal BoundCatchBlock Catch(
BoundExpression source,
BoundBlock block)
{
return new BoundCatchBlock(Syntax, ImmutableArray<LocalSymbol>.Empty, source, source.Type, exceptionFilterPrologueOpt: null, exceptionFilterOpt: null, body: block, isSynthesizedAsyncCatchAll: false);
}
internal BoundTryStatement Fault(BoundBlock tryBlock, BoundBlock faultBlock)
{
return new BoundTryStatement(Syntax, tryBlock, ImmutableArray<BoundCatchBlock>.Empty, faultBlock, finallyLabelOpt: null, preferFaultHandler: true);
}
internal BoundExpression NullOrDefault(TypeSymbol typeSymbol)
{
return NullOrDefault(typeSymbol, this.Syntax);
}
internal static BoundExpression NullOrDefault(TypeSymbol typeSymbol, SyntaxNode syntax)
{
return typeSymbol.IsReferenceType ? Null(typeSymbol, syntax) : Default(typeSymbol, syntax);
}
internal BoundExpression Not(BoundExpression expression)
{
Debug.Assert(expression is { Type: { SpecialType: CodeAnalysis.SpecialType.System_Boolean } });
return new BoundUnaryOperator(expression.Syntax, UnaryOperatorKind.BoolLogicalNegation, expression, null, null, constrainedToTypeOpt: null, LookupResultKind.Viable, expression.Type);
}
/// <summary>
/// Takes an expression and returns the bound local expression "temp"
/// and the bound assignment expression "temp = expr".
/// </summary>
public BoundLocal StoreToTemp(
BoundExpression argument,
out BoundAssignmentOperator store,
RefKind refKind = RefKind.None,
SynthesizedLocalKind kind = SynthesizedLocalKind.LoweringTemp,
SyntaxNode? syntaxOpt = null
#if DEBUG
, [CallerLineNumber] int callerLineNumber = 0
, [CallerFilePath] string? callerFilePath = null
#endif
)
{
Debug.Assert(argument.Type is { });
MethodSymbol? containingMethod = this.CurrentFunction;
Debug.Assert(containingMethod is { });
switch (refKind)
{
case RefKind.Out:
refKind = RefKind.Ref;
break;
case RefKind.In:
if (!Binder.HasHome(argument,
Binder.AddressKind.ReadOnly,
containingMethod,
Compilation.IsPeVerifyCompatEnabled,
stackLocalsOpt: null))
{
// If there was an explicit 'in' on the argument then we should have verified
// earlier that we always have a home.
Debug.Assert(argument.GetRefKind() != RefKind.In);
refKind = RefKind.None;
}
break;
case RefKindExtensions.StrictIn:
case RefKind.None:
case RefKind.Ref:
break;
default:
throw ExceptionUtilities.UnexpectedValue(refKind);
}
var syntax = argument.Syntax;
var type = argument.Type;
var local = new BoundLocal(
syntax,
new SynthesizedLocal(
containingMethod,
TypeWithAnnotations.Create(type),
kind,
#if DEBUG
createdAtLineNumber: callerLineNumber,
createdAtFilePath: callerFilePath,
#endif
syntaxOpt: syntaxOpt ?? (kind.IsLongLived() ? syntax : null),
isPinned: false,
refKind: refKind),
null,
type);
store = new BoundAssignmentOperator(
syntax,
local,
argument,
refKind != RefKind.None,
type);
return local;
}
internal BoundStatement NoOp(NoOpStatementFlavor noOpStatementFlavor)
{
return new BoundNoOpStatement(Syntax, noOpStatementFlavor);
}
internal BoundLocal MakeTempForDiscard(BoundDiscardExpression node, ArrayBuilder<LocalSymbol> temps)
{
LocalSymbol temp;
BoundLocal result = MakeTempForDiscard(node, out temp);
temps.Add(temp);
return result;
}
internal BoundLocal MakeTempForDiscard(BoundDiscardExpression node, out LocalSymbol temp)
{
Debug.Assert(node.Type is { });
temp = new SynthesizedLocal(this.CurrentFunction, TypeWithAnnotations.Create(node.Type), SynthesizedLocalKind.LoweringTemp);
return new BoundLocal(node.Syntax, temp, constantValueOpt: null, type: node.Type) { WasCompilerGenerated = true };
}
internal ImmutableArray<BoundExpression> MakeTempsForDiscardArguments(ImmutableArray<BoundExpression> arguments, ArrayBuilder<LocalSymbol> builder)
{
var discardsPresent = arguments.Any(a => a.Kind == BoundKind.DiscardExpression);
if (discardsPresent)
{
arguments = arguments.SelectAsArray(
(arg, t) => arg.Kind == BoundKind.DiscardExpression ? t.factory.MakeTempForDiscard((BoundDiscardExpression)arg, t.builder) : arg,
(factory: this, builder: builder));
}
return arguments;
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationConstructorInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationConstructorInfo
{
private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new();
private readonly bool _isPrimaryConstructor;
private readonly bool _isUnsafe;
private readonly string _typeName;
private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments;
private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments;
private readonly ImmutableArray<SyntaxNode> _statements;
private CodeGenerationConstructorInfo(
bool isPrimaryConstructor,
bool isUnsafe,
string typeName,
ImmutableArray<SyntaxNode> statements,
ImmutableArray<SyntaxNode> baseConstructorArguments,
ImmutableArray<SyntaxNode> thisConstructorArguments)
{
_isPrimaryConstructor = isPrimaryConstructor;
_isUnsafe = isUnsafe;
_typeName = typeName;
_statements = statements;
_baseConstructorArguments = baseConstructorArguments;
_thisConstructorArguments = thisConstructorArguments;
}
public static void Attach(
IMethodSymbol constructor,
bool isPrimaryConstructor,
bool isUnsafe,
string typeName,
ImmutableArray<SyntaxNode> statements,
ImmutableArray<SyntaxNode> baseConstructorArguments,
ImmutableArray<SyntaxNode> thisConstructorArguments)
{
var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments);
s_constructorToInfoMap.Add(constructor, info);
}
private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method)
{
s_constructorToInfoMap.TryGetValue(method, out var info);
return info;
}
public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor)
=> GetThisConstructorArgumentsOpt(GetInfo(constructor));
public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor)
=> GetBaseConstructorArgumentsOpt(GetInfo(constructor));
public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor)
=> GetStatements(GetInfo(constructor));
public static string GetTypeName(IMethodSymbol constructor)
=> GetTypeName(GetInfo(constructor), constructor);
public static bool GetIsUnsafe(IMethodSymbol constructor)
=> GetIsUnsafe(GetInfo(constructor));
public static bool GetIsPrimaryConstructor(IMethodSymbol constructor)
=> GetIsPrimaryConstructor(GetInfo(constructor));
private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info)
=> info?._thisConstructorArguments ?? default;
private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info)
=> info?._baseConstructorArguments ?? default;
private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info)
=> info?._statements ?? default;
private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor)
=> info == null ? constructor.ContainingType.Name : info._typeName;
private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info)
=> info?._isUnsafe ?? false;
private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info)
=> info?._isPrimaryConstructor ?? false;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationConstructorInfo
{
private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new();
private readonly bool _isPrimaryConstructor;
private readonly bool _isUnsafe;
private readonly string _typeName;
private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments;
private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments;
private readonly ImmutableArray<SyntaxNode> _statements;
private CodeGenerationConstructorInfo(
bool isPrimaryConstructor,
bool isUnsafe,
string typeName,
ImmutableArray<SyntaxNode> statements,
ImmutableArray<SyntaxNode> baseConstructorArguments,
ImmutableArray<SyntaxNode> thisConstructorArguments)
{
_isPrimaryConstructor = isPrimaryConstructor;
_isUnsafe = isUnsafe;
_typeName = typeName;
_statements = statements;
_baseConstructorArguments = baseConstructorArguments;
_thisConstructorArguments = thisConstructorArguments;
}
public static void Attach(
IMethodSymbol constructor,
bool isPrimaryConstructor,
bool isUnsafe,
string typeName,
ImmutableArray<SyntaxNode> statements,
ImmutableArray<SyntaxNode> baseConstructorArguments,
ImmutableArray<SyntaxNode> thisConstructorArguments)
{
var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments);
s_constructorToInfoMap.Add(constructor, info);
}
private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method)
{
s_constructorToInfoMap.TryGetValue(method, out var info);
return info;
}
public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor)
=> GetThisConstructorArgumentsOpt(GetInfo(constructor));
public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor)
=> GetBaseConstructorArgumentsOpt(GetInfo(constructor));
public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor)
=> GetStatements(GetInfo(constructor));
public static string GetTypeName(IMethodSymbol constructor)
=> GetTypeName(GetInfo(constructor), constructor);
public static bool GetIsUnsafe(IMethodSymbol constructor)
=> GetIsUnsafe(GetInfo(constructor));
public static bool GetIsPrimaryConstructor(IMethodSymbol constructor)
=> GetIsPrimaryConstructor(GetInfo(constructor));
private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info)
=> info?._thisConstructorArguments ?? default;
private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info)
=> info?._baseConstructorArguments ?? default;
private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info)
=> info?._statements ?? default;
private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor)
=> info == null ? constructor.ContainingType.Name : info._typeName;
private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info)
=> info?._isUnsafe ?? false;
private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info)
=> info?._isPrimaryConstructor ?? false;
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/CSharp/Portable/CodeGen/CodeGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal sealed partial class CodeGenerator
{
private readonly MethodSymbol _method;
// Syntax of the method body (block or an expression) being emitted,
// or null if the method being emitted isn't a source method.
// If we are emitting a lambda this is its body.
private readonly SyntaxNode _methodBodySyntaxOpt;
private readonly BoundStatement _boundBody;
private readonly ILBuilder _builder;
private readonly PEModuleBuilder _module;
private readonly DiagnosticBag _diagnostics;
private readonly ILEmitStyle _ilEmitStyle;
private readonly bool _emitPdbSequencePoints;
private readonly HashSet<LocalSymbol> _stackLocals;
// There are scenarios where rvalues need to be passed to ref/in parameters
// in such cases the values must be spilled into temps and retained for the entirety of
// the most encompassing expression.
private ArrayBuilder<LocalDefinition> _expressionTemps;
// not 0 when in a protected region with a handler.
private int _tryNestingLevel;
private readonly SynthesizedLocalOrdinalsDispenser _synthesizedLocalOrdinals = new SynthesizedLocalOrdinalsDispenser();
private int _uniqueNameId;
// label used when return is emitted in a form of store/goto
private static readonly object s_returnLabel = new object();
private int _asyncCatchHandlerOffset = -1;
private ArrayBuilder<int> _asyncYieldPoints;
private ArrayBuilder<int> _asyncResumePoints;
/// <summary>
/// In some cases returns are handled as gotos to return epilogue.
/// This is used to track the state of the epilogue.
/// </summary>
private IndirectReturnState _indirectReturnState;
/// <summary>
/// Used to implement <see cref="BoundSavePreviousSequencePoint"/> and <see cref="BoundRestorePreviousSequencePoint"/>.
/// </summary>
private PooledDictionary<object, TextSpan> _savedSequencePoints;
private enum IndirectReturnState : byte
{
NotNeeded = 0, // did not see indirect returns
Needed = 1, // saw indirect return and need to emit return sequence
Emitted = 2, // return sequence has been emitted
}
private LocalDefinition _returnTemp;
/// <summary>
/// True if there was a <see cref="ILOpCode.Localloc"/> anywhere in the method. This will
/// affect whether or not we require the locals init flag to be marked, since locals init
/// affects <see cref="ILOpCode.Localloc"/>.
/// </summary>
private bool _sawStackalloc;
public CodeGenerator(
MethodSymbol method,
BoundStatement boundBody,
ILBuilder builder,
PEModuleBuilder moduleBuilder,
DiagnosticBag diagnostics,
OptimizationLevel optimizations,
bool emittingPdb)
{
Debug.Assert((object)method != null);
Debug.Assert(boundBody != null);
Debug.Assert(builder != null);
Debug.Assert(moduleBuilder != null);
Debug.Assert(diagnostics != null);
_method = method;
_boundBody = boundBody;
_builder = builder;
_module = moduleBuilder;
_diagnostics = diagnostics;
if (!method.GenerateDebugInfo)
{
// Always optimize synthesized methods that don't contain user code.
//
// Specifically, always optimize synthesized explicit interface implementation methods
// (aka bridge methods) with by-ref returns because peverify produces errors if we
// return a ref local (which the return local will be in such cases).
_ilEmitStyle = ILEmitStyle.Release;
}
else
{
if (optimizations == OptimizationLevel.Debug)
{
_ilEmitStyle = ILEmitStyle.Debug;
}
else
{
_ilEmitStyle = IsDebugPlus() ?
ILEmitStyle.DebugFriendlyRelease :
ILEmitStyle.Release;
}
}
// Emit sequence points unless
// - the PDBs are not being generated
// - debug information for the method is not generated since the method does not contain
// user code that can be stepped through, or changed during EnC.
//
// This setting only affects generating PDB sequence points, it shall not affect generated IL in any way.
_emitPdbSequencePoints = emittingPdb && method.GenerateDebugInfo;
try
{
_boundBody = Optimizer.Optimize(
boundBody,
debugFriendly: _ilEmitStyle != ILEmitStyle.Release,
stackLocals: out _stackLocals);
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(diagnostics);
_boundBody = boundBody;
}
var sourceMethod = method as SourceMemberMethodSymbol;
(BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody) = sourceMethod?.Bodies ?? default;
_methodBodySyntaxOpt = (SyntaxNode)blockBody ?? expressionBody ?? sourceMethod?.SyntaxNode;
}
private bool IsDebugPlus()
{
return _module.Compilation.Options.DebugPlusMode;
}
private bool IsPeVerifyCompatEnabled() => _module.Compilation.IsPeVerifyCompatEnabled;
private LocalDefinition LazyReturnTemp
{
get
{
var result = _returnTemp;
if (result == null)
{
Debug.Assert(!_method.ReturnsVoid, "returning something from void method?");
var slotConstraints = _method.RefKind == RefKind.None
? LocalSlotConstraints.None
: LocalSlotConstraints.ByRef;
var bodySyntax = _methodBodySyntaxOpt;
if (_ilEmitStyle == ILEmitStyle.Debug && bodySyntax != null)
{
int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(bodySyntax), bodySyntax.SyntaxTree);
var localSymbol = new SynthesizedLocal(_method, _method.ReturnTypeWithAnnotations, SynthesizedLocalKind.FunctionReturnValue, bodySyntax);
result = _builder.LocalSlotManager.DeclareLocal(
type: _module.Translate(localSymbol.Type, bodySyntax, _diagnostics),
symbol: localSymbol,
name: null,
kind: localSymbol.SynthesizedKind,
id: new LocalDebugId(syntaxOffset, ordinal: 0),
pdbAttributes: localSymbol.SynthesizedKind.PdbAttributes(),
constraints: slotConstraints,
dynamicTransformFlags: ImmutableArray<bool>.Empty,
tupleElementNames: ImmutableArray<string>.Empty,
isSlotReusable: false);
}
else
{
result = AllocateTemp(_method.ReturnType, _boundBody.Syntax, slotConstraints);
}
_returnTemp = result;
}
return result;
}
}
internal static bool IsStackLocal(LocalSymbol local, HashSet<LocalSymbol> stackLocalsOpt)
=> stackLocalsOpt?.Contains(local) ?? false;
private bool IsStackLocal(LocalSymbol local) => IsStackLocal(local, _stackLocals);
public void Generate(out bool hasStackalloc)
{
this.GenerateImpl();
hasStackalloc = _sawStackalloc;
Debug.Assert(_asyncCatchHandlerOffset < 0);
Debug.Assert(_asyncYieldPoints == null);
Debug.Assert(_asyncResumePoints == null);
}
public void Generate(
out int asyncCatchHandlerOffset,
out ImmutableArray<int> asyncYieldPoints,
out ImmutableArray<int> asyncResumePoints,
out bool hasStackAlloc)
{
this.GenerateImpl();
hasStackAlloc = _sawStackalloc;
Debug.Assert(_asyncCatchHandlerOffset >= 0);
asyncCatchHandlerOffset = _builder.GetILOffsetFromMarker(_asyncCatchHandlerOffset);
ArrayBuilder<int> yieldPoints = _asyncYieldPoints;
ArrayBuilder<int> resumePoints = _asyncResumePoints;
Debug.Assert((yieldPoints == null) == (resumePoints == null));
if (yieldPoints == null)
{
asyncYieldPoints = ImmutableArray<int>.Empty;
asyncResumePoints = ImmutableArray<int>.Empty;
}
else
{
var yieldPointBuilder = ArrayBuilder<int>.GetInstance();
var resumePointBuilder = ArrayBuilder<int>.GetInstance();
int n = yieldPoints.Count;
for (int i = 0; i < n; i++)
{
int yieldOffset = _builder.GetILOffsetFromMarker(yieldPoints[i]);
int resumeOffset = _builder.GetILOffsetFromMarker(resumePoints[i]);
Debug.Assert(resumeOffset >= 0); // resume marker should always be reachable from dispatch
// yield point may not be reachable if the whole
// await is not reachable; we just ignore such awaits
if (yieldOffset > 0)
{
yieldPointBuilder.Add(yieldOffset);
resumePointBuilder.Add(resumeOffset);
}
}
asyncYieldPoints = yieldPointBuilder.ToImmutableAndFree();
asyncResumePoints = resumePointBuilder.ToImmutableAndFree();
yieldPoints.Free();
resumePoints.Free();
}
}
private void GenerateImpl()
{
SetInitialDebugDocument();
// Synthesized methods should have a sequence point
// at offset 0 to ensure correct stepping behavior.
if (_emitPdbSequencePoints && _method.IsImplicitlyDeclared)
{
_builder.DefineInitialHiddenSequencePoint();
}
try
{
EmitStatement(_boundBody);
if (_indirectReturnState == IndirectReturnState.Needed)
{
// it is unfortunate that return was not handled while we were in scope of the method
// it can happen in rare cases involving exception handling (for example all returns were from a try)
// in such case we can still handle return here.
HandleReturn();
}
if (!_diagnostics.HasAnyErrors())
{
_builder.Realize();
}
}
catch (EmitCancelledException)
{
Debug.Assert(_diagnostics.HasAnyErrors());
}
_synthesizedLocalOrdinals.Free();
Debug.Assert(!(_expressionTemps?.Count > 0), "leaking expression temps?");
_expressionTemps?.Free();
_savedSequencePoints?.Free();
}
private void HandleReturn()
{
_builder.MarkLabel(s_returnLabel);
Debug.Assert(_method.ReturnsVoid == (_returnTemp == null));
if (_emitPdbSequencePoints && !_method.IsIterator && !_method.IsAsync)
{
// In debug mode user could set a breakpoint on the last "}" of the method and
// expect to hit it before exiting the method.
// We do it by rewriting all returns into a jump to an Exit label
// and mark the Exit sequence with sequence point for the span of the last "}".
BlockSyntax blockSyntax = _methodBodySyntaxOpt as BlockSyntax;
if (blockSyntax != null)
{
EmitSequencePoint(blockSyntax.SyntaxTree, blockSyntax.CloseBraceToken.Span);
}
}
if (_returnTemp != null)
{
_builder.EmitLocalLoad(LazyReturnTemp);
_builder.EmitRet(false);
}
else
{
_builder.EmitRet(true);
}
_indirectReturnState = IndirectReturnState.Emitted;
}
private void EmitTypeReferenceToken(Cci.ITypeReference symbol, SyntaxNode syntaxNode)
{
_builder.EmitToken(symbol, syntaxNode, _diagnostics);
}
private void EmitSymbolToken(TypeSymbol symbol, SyntaxNode syntaxNode)
{
EmitTypeReferenceToken(_module.Translate(symbol, syntaxNode, _diagnostics), syntaxNode);
}
private void EmitSymbolToken(MethodSymbol method, SyntaxNode syntaxNode, BoundArgListOperator optArgList, bool encodeAsRawDefinitionToken = false)
{
_builder.EmitToken(_module.Translate(method, syntaxNode, _diagnostics, optArgList, needDeclaration: encodeAsRawDefinitionToken), syntaxNode, _diagnostics, encodeAsRawDefinitionToken);
}
private void EmitSymbolToken(FieldSymbol symbol, SyntaxNode syntaxNode)
{
_builder.EmitToken(_module.Translate(symbol, syntaxNode, _diagnostics), syntaxNode, _diagnostics);
}
private void EmitSignatureToken(FunctionPointerTypeSymbol symbol, SyntaxNode syntaxNode)
{
_builder.EmitToken(_module.Translate(symbol).Signature, syntaxNode, _diagnostics);
}
private void EmitSequencePointStatement(BoundSequencePoint node)
{
SyntaxNode syntax = node.Syntax;
if (_emitPdbSequencePoints)
{
if (syntax == null) //Null syntax indicates hidden sequence point (not equivalent to WasCompilerGenerated)
{
EmitHiddenSequencePoint();
}
else
{
EmitSequencePoint(syntax);
}
}
BoundStatement statement = node.StatementOpt;
int instructionsEmitted = 0;
if (statement != null)
{
instructionsEmitted = this.EmitStatementAndCountInstructions(statement);
}
if (instructionsEmitted == 0 && syntax != null && _ilEmitStyle == ILEmitStyle.Debug)
{
// if there was no code emitted, then emit nop
// otherwise this point could get associated with some random statement, possibly in a wrong scope
_builder.EmitOpCode(ILOpCode.Nop);
}
}
private void EmitSequencePointStatement(BoundSequencePointWithSpan node)
{
TextSpan span = node.Span;
if (span != default(TextSpan) && _emitPdbSequencePoints)
{
this.EmitSequencePoint(node.SyntaxTree, span);
}
BoundStatement statement = node.StatementOpt;
int instructionsEmitted = 0;
if (statement != null)
{
instructionsEmitted = this.EmitStatementAndCountInstructions(statement);
}
if (instructionsEmitted == 0 && span != default(TextSpan) && _ilEmitStyle == ILEmitStyle.Debug)
{
// if there was no code emitted, then emit nop
// otherwise this point could get associated with some random statement, possibly in a wrong scope
_builder.EmitOpCode(ILOpCode.Nop);
}
}
private void EmitSavePreviousSequencePoint(BoundSavePreviousSequencePoint statement)
{
if (!_emitPdbSequencePoints)
return;
ArrayBuilder<RawSequencePoint> sequencePoints = _builder.SeqPointsOpt;
if (sequencePoints is null)
return;
for (int i = sequencePoints.Count - 1; i >= 0; i--)
{
var span = sequencePoints[i].Span;
if (span == RawSequencePoint.HiddenSequencePointSpan)
continue;
// Found the previous non-hidden sequence point. Save it.
_savedSequencePoints ??= PooledDictionary<object, TextSpan>.GetInstance();
_savedSequencePoints.Add(statement.Identifier, span);
return;
}
}
private void EmitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node)
{
Debug.Assert(node.Syntax is { });
if (_savedSequencePoints is null || !_savedSequencePoints.TryGetValue(node.Identifier, out var span))
return;
EmitStepThroughSequencePoint(node.Syntax.SyntaxTree, span);
}
private void EmitStepThroughSequencePoint(BoundStepThroughSequencePoint node)
{
EmitStepThroughSequencePoint(node.Syntax.SyntaxTree, node.Span);
}
private void EmitStepThroughSequencePoint(SyntaxTree syntaxTree, TextSpan span)
{
if (!_emitPdbSequencePoints)
return;
var label = new object();
// The IL builder is eager to discard unreachable code, so
// we fool it by branching on a condition that is always true at runtime.
_builder.EmitConstantValue(ConstantValue.Create(true));
_builder.EmitBranch(ILOpCode.Brtrue, label);
EmitSequencePoint(syntaxTree, span);
_builder.EmitOpCode(ILOpCode.Nop);
_builder.MarkLabel(label);
EmitHiddenSequencePoint();
}
private void SetInitialDebugDocument()
{
if (_emitPdbSequencePoints && _methodBodySyntaxOpt != null)
{
// If methodBlockSyntax is available (i.e. we're in a SourceMethodSymbol), then
// provide the IL builder with our best guess at the appropriate debug document.
// If we don't and this is hidden sequence point precedes all non-hidden sequence
// points, then the IL Builder will drop the sequence point for lack of a document.
// This negatively impacts the scenario where we insert hidden sequence points at
// the beginnings of methods so that step-into (F11) will handle them correctly.
_builder.SetInitialDebugDocument(_methodBodySyntaxOpt.SyntaxTree);
}
}
private void EmitHiddenSequencePoint()
{
Debug.Assert(_emitPdbSequencePoints);
_builder.DefineHiddenSequencePoint();
}
private void EmitSequencePoint(SyntaxNode syntax)
{
EmitSequencePoint(syntax.SyntaxTree, syntax.Span);
}
private TextSpan EmitSequencePoint(SyntaxTree syntaxTree, TextSpan span)
{
Debug.Assert(syntaxTree != null);
Debug.Assert(_emitPdbSequencePoints);
_builder.DefineSequencePoint(syntaxTree, span);
return span;
}
private void AddExpressionTemp(LocalDefinition temp)
{
// in some cases like stack locals, there is no slot allocated.
if (temp == null)
{
return;
}
ArrayBuilder<LocalDefinition> exprTemps = _expressionTemps;
if (exprTemps == null)
{
exprTemps = ArrayBuilder<LocalDefinition>.GetInstance();
_expressionTemps = exprTemps;
}
Debug.Assert(!exprTemps.Contains(temp));
exprTemps.Add(temp);
}
private void ReleaseExpressionTemps()
{
if (_expressionTemps?.Count > 0)
{
// release in reverse order to keep same temps on top of the temp stack if possible
for (int i = _expressionTemps.Count - 1; i >= 0; i--)
{
var temp = _expressionTemps[i];
FreeTemp(temp);
}
_expressionTemps.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.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal sealed partial class CodeGenerator
{
private readonly MethodSymbol _method;
// Syntax of the method body (block or an expression) being emitted,
// or null if the method being emitted isn't a source method.
// If we are emitting a lambda this is its body.
private readonly SyntaxNode _methodBodySyntaxOpt;
private readonly BoundStatement _boundBody;
private readonly ILBuilder _builder;
private readonly PEModuleBuilder _module;
private readonly DiagnosticBag _diagnostics;
private readonly ILEmitStyle _ilEmitStyle;
private readonly bool _emitPdbSequencePoints;
private readonly HashSet<LocalSymbol> _stackLocals;
// There are scenarios where rvalues need to be passed to ref/in parameters
// in such cases the values must be spilled into temps and retained for the entirety of
// the most encompassing expression.
private ArrayBuilder<LocalDefinition> _expressionTemps;
// not 0 when in a protected region with a handler.
private int _tryNestingLevel;
private readonly SynthesizedLocalOrdinalsDispenser _synthesizedLocalOrdinals = new SynthesizedLocalOrdinalsDispenser();
private int _uniqueNameId;
// label used when return is emitted in a form of store/goto
private static readonly object s_returnLabel = new object();
private int _asyncCatchHandlerOffset = -1;
private ArrayBuilder<int> _asyncYieldPoints;
private ArrayBuilder<int> _asyncResumePoints;
/// <summary>
/// In some cases returns are handled as gotos to return epilogue.
/// This is used to track the state of the epilogue.
/// </summary>
private IndirectReturnState _indirectReturnState;
/// <summary>
/// Used to implement <see cref="BoundSavePreviousSequencePoint"/> and <see cref="BoundRestorePreviousSequencePoint"/>.
/// </summary>
private PooledDictionary<object, TextSpan> _savedSequencePoints;
private enum IndirectReturnState : byte
{
NotNeeded = 0, // did not see indirect returns
Needed = 1, // saw indirect return and need to emit return sequence
Emitted = 2, // return sequence has been emitted
}
private LocalDefinition _returnTemp;
/// <summary>
/// True if there was a <see cref="ILOpCode.Localloc"/> anywhere in the method. This will
/// affect whether or not we require the locals init flag to be marked, since locals init
/// affects <see cref="ILOpCode.Localloc"/>.
/// </summary>
private bool _sawStackalloc;
public CodeGenerator(
MethodSymbol method,
BoundStatement boundBody,
ILBuilder builder,
PEModuleBuilder moduleBuilder,
DiagnosticBag diagnostics,
OptimizationLevel optimizations,
bool emittingPdb)
{
Debug.Assert((object)method != null);
Debug.Assert(boundBody != null);
Debug.Assert(builder != null);
Debug.Assert(moduleBuilder != null);
Debug.Assert(diagnostics != null);
_method = method;
_boundBody = boundBody;
_builder = builder;
_module = moduleBuilder;
_diagnostics = diagnostics;
if (!method.GenerateDebugInfo)
{
// Always optimize synthesized methods that don't contain user code.
//
// Specifically, always optimize synthesized explicit interface implementation methods
// (aka bridge methods) with by-ref returns because peverify produces errors if we
// return a ref local (which the return local will be in such cases).
_ilEmitStyle = ILEmitStyle.Release;
}
else
{
if (optimizations == OptimizationLevel.Debug)
{
_ilEmitStyle = ILEmitStyle.Debug;
}
else
{
_ilEmitStyle = IsDebugPlus() ?
ILEmitStyle.DebugFriendlyRelease :
ILEmitStyle.Release;
}
}
// Emit sequence points unless
// - the PDBs are not being generated
// - debug information for the method is not generated since the method does not contain
// user code that can be stepped through, or changed during EnC.
//
// This setting only affects generating PDB sequence points, it shall not affect generated IL in any way.
_emitPdbSequencePoints = emittingPdb && method.GenerateDebugInfo;
try
{
_boundBody = Optimizer.Optimize(
boundBody,
debugFriendly: _ilEmitStyle != ILEmitStyle.Release,
stackLocals: out _stackLocals);
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(diagnostics);
_boundBody = boundBody;
}
var sourceMethod = method as SourceMemberMethodSymbol;
(BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody) = sourceMethod?.Bodies ?? default;
_methodBodySyntaxOpt = (SyntaxNode)blockBody ?? expressionBody ?? sourceMethod?.SyntaxNode;
}
private bool IsDebugPlus()
{
return _module.Compilation.Options.DebugPlusMode;
}
private bool IsPeVerifyCompatEnabled() => _module.Compilation.IsPeVerifyCompatEnabled;
private LocalDefinition LazyReturnTemp
{
get
{
var result = _returnTemp;
if (result == null)
{
Debug.Assert(!_method.ReturnsVoid, "returning something from void method?");
var slotConstraints = _method.RefKind == RefKind.None
? LocalSlotConstraints.None
: LocalSlotConstraints.ByRef;
var bodySyntax = _methodBodySyntaxOpt;
if (_ilEmitStyle == ILEmitStyle.Debug && bodySyntax != null)
{
int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(bodySyntax), bodySyntax.SyntaxTree);
var localSymbol = new SynthesizedLocal(_method, _method.ReturnTypeWithAnnotations, SynthesizedLocalKind.FunctionReturnValue, bodySyntax);
result = _builder.LocalSlotManager.DeclareLocal(
type: _module.Translate(localSymbol.Type, bodySyntax, _diagnostics),
symbol: localSymbol,
name: null,
kind: localSymbol.SynthesizedKind,
id: new LocalDebugId(syntaxOffset, ordinal: 0),
pdbAttributes: localSymbol.SynthesizedKind.PdbAttributes(),
constraints: slotConstraints,
dynamicTransformFlags: ImmutableArray<bool>.Empty,
tupleElementNames: ImmutableArray<string>.Empty,
isSlotReusable: false);
}
else
{
result = AllocateTemp(_method.ReturnType, _boundBody.Syntax, slotConstraints);
}
_returnTemp = result;
}
return result;
}
}
internal static bool IsStackLocal(LocalSymbol local, HashSet<LocalSymbol> stackLocalsOpt)
=> stackLocalsOpt?.Contains(local) ?? false;
private bool IsStackLocal(LocalSymbol local) => IsStackLocal(local, _stackLocals);
public void Generate(out bool hasStackalloc)
{
this.GenerateImpl();
hasStackalloc = _sawStackalloc;
Debug.Assert(_asyncCatchHandlerOffset < 0);
Debug.Assert(_asyncYieldPoints == null);
Debug.Assert(_asyncResumePoints == null);
}
public void Generate(
out int asyncCatchHandlerOffset,
out ImmutableArray<int> asyncYieldPoints,
out ImmutableArray<int> asyncResumePoints,
out bool hasStackAlloc)
{
this.GenerateImpl();
hasStackAlloc = _sawStackalloc;
Debug.Assert(_asyncCatchHandlerOffset >= 0);
asyncCatchHandlerOffset = _builder.GetILOffsetFromMarker(_asyncCatchHandlerOffset);
ArrayBuilder<int> yieldPoints = _asyncYieldPoints;
ArrayBuilder<int> resumePoints = _asyncResumePoints;
Debug.Assert((yieldPoints == null) == (resumePoints == null));
if (yieldPoints == null)
{
asyncYieldPoints = ImmutableArray<int>.Empty;
asyncResumePoints = ImmutableArray<int>.Empty;
}
else
{
var yieldPointBuilder = ArrayBuilder<int>.GetInstance();
var resumePointBuilder = ArrayBuilder<int>.GetInstance();
int n = yieldPoints.Count;
for (int i = 0; i < n; i++)
{
int yieldOffset = _builder.GetILOffsetFromMarker(yieldPoints[i]);
int resumeOffset = _builder.GetILOffsetFromMarker(resumePoints[i]);
Debug.Assert(resumeOffset >= 0); // resume marker should always be reachable from dispatch
// yield point may not be reachable if the whole
// await is not reachable; we just ignore such awaits
if (yieldOffset > 0)
{
yieldPointBuilder.Add(yieldOffset);
resumePointBuilder.Add(resumeOffset);
}
}
asyncYieldPoints = yieldPointBuilder.ToImmutableAndFree();
asyncResumePoints = resumePointBuilder.ToImmutableAndFree();
yieldPoints.Free();
resumePoints.Free();
}
}
private void GenerateImpl()
{
SetInitialDebugDocument();
// Synthesized methods should have a sequence point
// at offset 0 to ensure correct stepping behavior.
if (_emitPdbSequencePoints && _method.IsImplicitlyDeclared)
{
_builder.DefineInitialHiddenSequencePoint();
}
try
{
EmitStatement(_boundBody);
if (_indirectReturnState == IndirectReturnState.Needed)
{
// it is unfortunate that return was not handled while we were in scope of the method
// it can happen in rare cases involving exception handling (for example all returns were from a try)
// in such case we can still handle return here.
HandleReturn();
}
if (!_diagnostics.HasAnyErrors())
{
_builder.Realize();
}
}
catch (EmitCancelledException)
{
Debug.Assert(_diagnostics.HasAnyErrors());
}
_synthesizedLocalOrdinals.Free();
Debug.Assert(!(_expressionTemps?.Count > 0), "leaking expression temps?");
_expressionTemps?.Free();
_savedSequencePoints?.Free();
}
private void HandleReturn()
{
_builder.MarkLabel(s_returnLabel);
Debug.Assert(_method.ReturnsVoid == (_returnTemp == null));
if (_emitPdbSequencePoints && !_method.IsIterator && !_method.IsAsync)
{
// In debug mode user could set a breakpoint on the last "}" of the method and
// expect to hit it before exiting the method.
// We do it by rewriting all returns into a jump to an Exit label
// and mark the Exit sequence with sequence point for the span of the last "}".
BlockSyntax blockSyntax = _methodBodySyntaxOpt as BlockSyntax;
if (blockSyntax != null)
{
EmitSequencePoint(blockSyntax.SyntaxTree, blockSyntax.CloseBraceToken.Span);
}
}
if (_returnTemp != null)
{
_builder.EmitLocalLoad(LazyReturnTemp);
_builder.EmitRet(false);
}
else
{
_builder.EmitRet(true);
}
_indirectReturnState = IndirectReturnState.Emitted;
}
private void EmitTypeReferenceToken(Cci.ITypeReference symbol, SyntaxNode syntaxNode)
{
_builder.EmitToken(symbol, syntaxNode, _diagnostics);
}
private void EmitSymbolToken(TypeSymbol symbol, SyntaxNode syntaxNode)
{
EmitTypeReferenceToken(_module.Translate(symbol, syntaxNode, _diagnostics), syntaxNode);
}
private void EmitSymbolToken(MethodSymbol method, SyntaxNode syntaxNode, BoundArgListOperator optArgList, bool encodeAsRawDefinitionToken = false)
{
_builder.EmitToken(_module.Translate(method, syntaxNode, _diagnostics, optArgList, needDeclaration: encodeAsRawDefinitionToken), syntaxNode, _diagnostics, encodeAsRawDefinitionToken);
}
private void EmitSymbolToken(FieldSymbol symbol, SyntaxNode syntaxNode)
{
_builder.EmitToken(_module.Translate(symbol, syntaxNode, _diagnostics), syntaxNode, _diagnostics);
}
private void EmitSignatureToken(FunctionPointerTypeSymbol symbol, SyntaxNode syntaxNode)
{
_builder.EmitToken(_module.Translate(symbol).Signature, syntaxNode, _diagnostics);
}
private void EmitSequencePointStatement(BoundSequencePoint node)
{
SyntaxNode syntax = node.Syntax;
if (_emitPdbSequencePoints)
{
if (syntax == null) //Null syntax indicates hidden sequence point (not equivalent to WasCompilerGenerated)
{
EmitHiddenSequencePoint();
}
else
{
EmitSequencePoint(syntax);
}
}
BoundStatement statement = node.StatementOpt;
int instructionsEmitted = 0;
if (statement != null)
{
instructionsEmitted = this.EmitStatementAndCountInstructions(statement);
}
if (instructionsEmitted == 0 && syntax != null && _ilEmitStyle == ILEmitStyle.Debug)
{
// if there was no code emitted, then emit nop
// otherwise this point could get associated with some random statement, possibly in a wrong scope
_builder.EmitOpCode(ILOpCode.Nop);
}
}
private void EmitSequencePointStatement(BoundSequencePointWithSpan node)
{
TextSpan span = node.Span;
if (span != default(TextSpan) && _emitPdbSequencePoints)
{
this.EmitSequencePoint(node.SyntaxTree, span);
}
BoundStatement statement = node.StatementOpt;
int instructionsEmitted = 0;
if (statement != null)
{
instructionsEmitted = this.EmitStatementAndCountInstructions(statement);
}
if (instructionsEmitted == 0 && span != default(TextSpan) && _ilEmitStyle == ILEmitStyle.Debug)
{
// if there was no code emitted, then emit nop
// otherwise this point could get associated with some random statement, possibly in a wrong scope
_builder.EmitOpCode(ILOpCode.Nop);
}
}
private void EmitSavePreviousSequencePoint(BoundSavePreviousSequencePoint statement)
{
if (!_emitPdbSequencePoints)
return;
ArrayBuilder<RawSequencePoint> sequencePoints = _builder.SeqPointsOpt;
if (sequencePoints is null)
return;
for (int i = sequencePoints.Count - 1; i >= 0; i--)
{
var span = sequencePoints[i].Span;
if (span == RawSequencePoint.HiddenSequencePointSpan)
continue;
// Found the previous non-hidden sequence point. Save it.
_savedSequencePoints ??= PooledDictionary<object, TextSpan>.GetInstance();
_savedSequencePoints.Add(statement.Identifier, span);
return;
}
}
private void EmitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node)
{
Debug.Assert(node.Syntax is { });
if (_savedSequencePoints is null || !_savedSequencePoints.TryGetValue(node.Identifier, out var span))
return;
EmitStepThroughSequencePoint(node.Syntax.SyntaxTree, span);
}
private void EmitStepThroughSequencePoint(BoundStepThroughSequencePoint node)
{
EmitStepThroughSequencePoint(node.Syntax.SyntaxTree, node.Span);
}
private void EmitStepThroughSequencePoint(SyntaxTree syntaxTree, TextSpan span)
{
if (!_emitPdbSequencePoints)
return;
var label = new object();
// The IL builder is eager to discard unreachable code, so
// we fool it by branching on a condition that is always true at runtime.
_builder.EmitConstantValue(ConstantValue.Create(true));
_builder.EmitBranch(ILOpCode.Brtrue, label);
EmitSequencePoint(syntaxTree, span);
_builder.EmitOpCode(ILOpCode.Nop);
_builder.MarkLabel(label);
EmitHiddenSequencePoint();
}
private void SetInitialDebugDocument()
{
if (_emitPdbSequencePoints && _methodBodySyntaxOpt != null)
{
// If methodBlockSyntax is available (i.e. we're in a SourceMethodSymbol), then
// provide the IL builder with our best guess at the appropriate debug document.
// If we don't and this is hidden sequence point precedes all non-hidden sequence
// points, then the IL Builder will drop the sequence point for lack of a document.
// This negatively impacts the scenario where we insert hidden sequence points at
// the beginnings of methods so that step-into (F11) will handle them correctly.
_builder.SetInitialDebugDocument(_methodBodySyntaxOpt.SyntaxTree);
}
}
private void EmitHiddenSequencePoint()
{
Debug.Assert(_emitPdbSequencePoints);
_builder.DefineHiddenSequencePoint();
}
private void EmitSequencePoint(SyntaxNode syntax)
{
EmitSequencePoint(syntax.SyntaxTree, syntax.Span);
}
private TextSpan EmitSequencePoint(SyntaxTree syntaxTree, TextSpan span)
{
Debug.Assert(syntaxTree != null);
Debug.Assert(_emitPdbSequencePoints);
_builder.DefineSequencePoint(syntaxTree, span);
return span;
}
private void AddExpressionTemp(LocalDefinition temp)
{
// in some cases like stack locals, there is no slot allocated.
if (temp == null)
{
return;
}
ArrayBuilder<LocalDefinition> exprTemps = _expressionTemps;
if (exprTemps == null)
{
exprTemps = ArrayBuilder<LocalDefinition>.GetInstance();
_expressionTemps = exprTemps;
}
Debug.Assert(!exprTemps.Contains(temp));
exprTemps.Add(temp);
}
private void ReleaseExpressionTemps()
{
if (_expressionTemps?.Count > 0)
{
// release in reverse order to keep same temps on top of the temp stack if possible
for (int i = _expressionTemps.Count - 1; i >= 0; i--)
{
var temp = _expressionTemps[i];
FreeTemp(temp);
}
_expressionTemps.Clear();
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/EditorFeatures/Core.Wpf/InlineRename/HighlightTags/RenameFieldBackgroundAndBorderTagDefinition.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags
{
[Export(typeof(EditorFormatDefinition))]
[Name(RenameFieldBackgroundAndBorderTag.TagId)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
internal class RenameFieldBackgroundAndBorderTagDefinition : MarkerFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RenameFieldBackgroundAndBorderTagDefinition()
{
// The Border color should match the BackgroundColor from the
// InlineRenameFieldFormatDefinition.
this.Border = new Pen(new SolidColorBrush(Color.FromRgb(0xFF, 0xFF, 0xFF)), thickness: 2.0);
#if COCOA
this.BackgroundColor = Color.FromRgb(0xa6, 0xf1, 0xa6);
#else
this.BackgroundColor = Color.FromRgb(0xd3, 0xf8, 0xd3);
#endif
this.DisplayName = EditorFeaturesResources.Inline_Rename_Field_Background_and_Border;
// Needs to show above highlight references, but below the resolved/unresolved rename
// conflict tags.
this.ZOrder = 1;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags
{
[Export(typeof(EditorFormatDefinition))]
[Name(RenameFieldBackgroundAndBorderTag.TagId)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
internal class RenameFieldBackgroundAndBorderTagDefinition : MarkerFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RenameFieldBackgroundAndBorderTagDefinition()
{
// The Border color should match the BackgroundColor from the
// InlineRenameFieldFormatDefinition.
this.Border = new Pen(new SolidColorBrush(Color.FromRgb(0xFF, 0xFF, 0xFF)), thickness: 2.0);
#if COCOA
this.BackgroundColor = Color.FromRgb(0xa6, 0xf1, 0xa6);
#else
this.BackgroundColor = Color.FromRgb(0xd3, 0xf8, 0xd3);
#endif
this.DisplayName = EditorFeaturesResources.Inline_Rename_Field_Background_and_Border;
// Needs to show above highlight references, but below the resolved/unresolved rename
// conflict tags.
this.ZOrder = 1;
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Features/Core/Portable/Wrapping/AbstractCodeActionComputer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.Wrapping
{
internal abstract partial class AbstractSyntaxWrapper
{
/// <summary>
/// Class responsible for actually computing the entire set of code actions to offer the
/// user. Contains lots of helper functionality used by all the different Wrapper
/// implementations.
///
/// Specifically subclasses of this type can simply provide a list of code-actions to
/// perform. This type will then take those code actions and will ensure there aren't
/// multiple code actions that end up having the same effect on the document. For example,
/// a "wrap all" action may produce the same results as a "wrap long" action. In that case
/// this type will only keep around the first of those actions to prevent showing the user
/// something that will be unclear.
/// </summary>
protected abstract class AbstractCodeActionComputer<TWrapper> : ICodeActionComputer
where TWrapper : AbstractSyntaxWrapper
{
/// <summary>
/// Annotation used so that we can track the top-most node we want to format after
/// performing all our edits.
/// </summary>
private static readonly SyntaxAnnotation s_toFormatAnnotation = new();
protected readonly TWrapper Wrapper;
protected readonly Document OriginalDocument;
protected readonly SourceText OriginalSourceText;
protected readonly CancellationToken CancellationToken;
protected readonly bool UseTabs;
protected readonly int TabSize;
protected readonly string NewLine;
protected readonly int WrappingColumn;
protected readonly SyntaxTriviaList NewLineTrivia;
protected readonly SyntaxTriviaList SingleWhitespaceTrivia;
protected readonly SyntaxTriviaList NoTrivia;
/// <summary>
/// The contents of the documents we've created code-actions for. This is used so that
/// we can prevent creating multiple code actions that produce the same results.
/// </summary>
private readonly List<SyntaxNode> _seenDocumentRoots = new();
public AbstractCodeActionComputer(
TWrapper service,
Document document,
SourceText originalSourceText,
DocumentOptionSet options,
CancellationToken cancellationToken)
{
Wrapper = service;
OriginalDocument = document;
OriginalSourceText = originalSourceText;
CancellationToken = cancellationToken;
UseTabs = options.GetOption(FormattingOptions.UseTabs);
TabSize = options.GetOption(FormattingOptions.TabSize);
NewLine = options.GetOption(FormattingOptions.NewLine);
WrappingColumn = options.GetOption(FormattingOptions2.PreferredWrappingColumn);
var generator = SyntaxGenerator.GetGenerator(document);
var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>();
NewLineTrivia = new SyntaxTriviaList(generatorInternal.EndOfLine(NewLine));
SingleWhitespaceTrivia = new SyntaxTriviaList(generator.Whitespace(" "));
}
protected abstract Task<ImmutableArray<WrappingGroup>> ComputeWrappingGroupsAsync();
protected string GetSmartIndentationAfter(SyntaxNodeOrToken nodeOrToken)
{
var newSourceText = OriginalSourceText.WithChanges(new TextChange(new TextSpan(nodeOrToken.Span.End, 0), NewLine));
newSourceText = newSourceText.WithChanges(
new TextChange(TextSpan.FromBounds(nodeOrToken.Span.End + NewLine.Length, newSourceText.Length), ""));
var newDocument = OriginalDocument.WithText(newSourceText);
var indentationService = Wrapper.IndentationService;
var originalLineNumber = newSourceText.Lines.GetLineFromPosition(nodeOrToken.Span.End).LineNumber;
var desiredIndentation = indentationService.GetIndentation(
newDocument, originalLineNumber + 1,
FormattingOptions.IndentStyle.Smart,
CancellationToken);
var baseLine = newSourceText.Lines.GetLineFromPosition(desiredIndentation.BasePosition);
var baseOffsetInLine = desiredIndentation.BasePosition - baseLine.Start;
var indent = baseOffsetInLine + desiredIndentation.Offset;
var indentString = indent.CreateIndentationString(UseTabs, TabSize);
return indentString;
}
/// <summary>
/// Try to create a CodeAction representing these edits. Can return <see langword="null"/> in several
/// cases, including:
///
/// 1. No edits.
/// 2. Edits would change more than whitespace.
/// 3. A previous code action was created that already had the same effect.
/// </summary>
protected async Task<WrapItemsAction> TryCreateCodeActionAsync(
ImmutableArray<Edit> edits, string parentTitle, string title)
{
// First, rewrite the tree with the edits provided.
var (root, rewrittenRoot, spanToFormat) = await RewriteTreeAsync(edits).ConfigureAwait(false);
if (rewrittenRoot == null)
{
// Couldn't rewrite for some reason. No code action to create.
return null;
}
// Now, format the part of the tree that we edited. This will ensure we properly
// respect the user preferences around things like comma/operator spacing.
var formattedDocument = await FormatDocumentAsync(rewrittenRoot, spanToFormat).ConfigureAwait(false);
var formattedRoot = await formattedDocument.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false);
// Now, check if this new formatted tree matches our starting tree, or any of the
// trees we've already created for our other code actions. If so, we don't want to
// add this duplicative code action. Note: this check will actually run quickly.
// 'IsEquivalentTo' can return quickly when comparing equivalent green nodes. So
// all that we need to check is the spine of the change which will happen very
// quickly.
if (root.IsEquivalentTo(formattedRoot))
{
return null;
}
foreach (var seenRoot in _seenDocumentRoots)
{
if (seenRoot.IsEquivalentTo(formattedRoot))
{
return null;
}
}
// This is a genuinely different code action from all previous ones we've created.
// Store the root so we don't just end up creating this code action again.
_seenDocumentRoots.Add(formattedRoot);
return new WrapItemsAction(title, parentTitle, _ => Task.FromResult(formattedDocument));
}
private async Task<Document> FormatDocumentAsync(SyntaxNode rewrittenRoot, TextSpan spanToFormat)
{
var newDocument = OriginalDocument.WithSyntaxRoot(rewrittenRoot);
var formattedDocument = await Formatter.FormatAsync(
newDocument, spanToFormat, cancellationToken: CancellationToken).ConfigureAwait(false);
return formattedDocument;
}
private async Task<(SyntaxNode root, SyntaxNode rewrittenRoot, TextSpan spanToFormat)> RewriteTreeAsync(ImmutableArray<Edit> edits)
{
using var _1 = PooledDictionary<SyntaxToken, SyntaxTriviaList>.GetInstance(out var leftTokenToTrailingTrivia);
using var _2 = PooledDictionary<SyntaxToken, SyntaxTriviaList>.GetInstance(out var rightTokenToLeadingTrivia);
foreach (var edit in edits)
{
var span = TextSpan.FromBounds(edit.Left.Span.End, edit.Right.Span.Start);
var text = OriginalSourceText.ToString(span);
if (!IsSafeToRemove(text))
{
// editing some piece of non-whitespace trivia. We don't support this.
return default;
}
// Make sure we're not about to make an edit that just changes the code to what
// is already there.
if (text != edit.GetNewTrivia())
{
leftTokenToTrailingTrivia.Add(edit.Left, edit.NewLeftTrailingTrivia);
rightTokenToLeadingTrivia.Add(edit.Right, edit.NewRightLeadingTrivia);
}
}
if (leftTokenToTrailingTrivia.Count == 0)
{
// No actual edits that would change anything. Nothing to do.
return default;
}
return await RewriteTreeAsync(
leftTokenToTrailingTrivia, rightTokenToLeadingTrivia).ConfigureAwait(false);
}
private static bool IsSafeToRemove(string text)
{
foreach (var ch in text)
{
// It's safe to remove whitespace between tokens, or the VB line-continuation character.
if (!char.IsWhiteSpace(ch) && ch != '_')
{
return false;
}
}
return true;
}
private async Task<(SyntaxNode root, SyntaxNode rewrittenRoot, TextSpan spanToFormat)> RewriteTreeAsync(
Dictionary<SyntaxToken, SyntaxTriviaList> leftTokenToTrailingTrivia,
Dictionary<SyntaxToken, SyntaxTriviaList> rightTokenToLeadingTrivia)
{
var root = await OriginalDocument.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false);
var tokens = leftTokenToTrailingTrivia.Keys.Concat(rightTokenToLeadingTrivia.Keys).Distinct().ToImmutableArray();
// Find the closest node that contains all the tokens we're editing. That's the
// node we'll format at the end. This will ensure that all formattin respects
// user settings for things like spacing around commas/operators/etc.
var nodeToFormat = tokens.SelectAsArray(t => t.Parent).FindInnermostCommonNode<SyntaxNode>();
// Rewrite the tree performing the following actions:
//
// 1. Add an annotation to nodeToFormat so that we can find that node again after
// updating all tokens.
//
// 2. Hit all tokens in the two passed in maps, and update their leading/trailing
// trivia accordingly.
var rewrittenRoot = root.ReplaceSyntax(
nodes: new[] { nodeToFormat },
computeReplacementNode: (oldNode, newNode) => newNode.WithAdditionalAnnotations(s_toFormatAnnotation),
tokens: leftTokenToTrailingTrivia.Keys.Concat(rightTokenToLeadingTrivia.Keys).Distinct(),
computeReplacementToken: (oldToken, newToken) =>
{
if (leftTokenToTrailingTrivia.TryGetValue(oldToken, out var trailingTrivia))
{
newToken = newToken.WithTrailingTrivia(trailingTrivia);
}
if (rightTokenToLeadingTrivia.TryGetValue(oldToken, out var leadingTrivia))
{
newToken = newToken.WithLeadingTrivia(leadingTrivia);
}
return newToken;
},
trivia: null,
computeReplacementTrivia: null);
var trackedNode = rewrittenRoot.GetAnnotatedNodes(s_toFormatAnnotation).Single();
return (root, rewrittenRoot, trackedNode.Span);
}
public async Task<ImmutableArray<CodeAction>> GetTopLevelCodeActionsAsync()
{
// Ask subclass to produce whole nested list of wrapping code actions
var wrappingGroups = await ComputeWrappingGroupsAsync().ConfigureAwait(false);
var result = ArrayBuilder<CodeAction>.GetInstance();
foreach (var group in wrappingGroups)
{
// if a group is empty just ignore it.
var wrappingActions = group.WrappingActions.WhereNotNull().ToImmutableArray();
if (wrappingActions.Length == 0)
{
continue;
}
// If a group only has one item, and subclass says the item is inlinable,
// then just directly return that nested item as a top level item.
if (wrappingActions.Length == 1 && group.IsInlinable)
{
result.Add(wrappingActions[0]);
continue;
}
// Otherwise, sort items and add to the resultant list
var sorted = WrapItemsAction.SortActionsByMostRecentlyUsed(ImmutableArray<CodeAction>.CastUp(wrappingActions));
// Make our code action low priority. This option will be offered *a lot*, and
// much of the time will not be something the user particularly wants to do.
// It should be offered after all other normal refactorings.
result.Add(new CodeActionWithNestedActions(
wrappingActions[0].ParentTitle, sorted,
group.IsInlinable, CodeActionPriority.Low));
}
// Finally, sort the topmost list we're building and return that. This ensures that
// both the top level items and the nested items are ordered appropriate.
return WrapItemsAction.SortActionsByMostRecentlyUsed(result.ToImmutableAndFree());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.Wrapping
{
internal abstract partial class AbstractSyntaxWrapper
{
/// <summary>
/// Class responsible for actually computing the entire set of code actions to offer the
/// user. Contains lots of helper functionality used by all the different Wrapper
/// implementations.
///
/// Specifically subclasses of this type can simply provide a list of code-actions to
/// perform. This type will then take those code actions and will ensure there aren't
/// multiple code actions that end up having the same effect on the document. For example,
/// a "wrap all" action may produce the same results as a "wrap long" action. In that case
/// this type will only keep around the first of those actions to prevent showing the user
/// something that will be unclear.
/// </summary>
protected abstract class AbstractCodeActionComputer<TWrapper> : ICodeActionComputer
where TWrapper : AbstractSyntaxWrapper
{
/// <summary>
/// Annotation used so that we can track the top-most node we want to format after
/// performing all our edits.
/// </summary>
private static readonly SyntaxAnnotation s_toFormatAnnotation = new();
protected readonly TWrapper Wrapper;
protected readonly Document OriginalDocument;
protected readonly SourceText OriginalSourceText;
protected readonly CancellationToken CancellationToken;
protected readonly bool UseTabs;
protected readonly int TabSize;
protected readonly string NewLine;
protected readonly int WrappingColumn;
protected readonly SyntaxTriviaList NewLineTrivia;
protected readonly SyntaxTriviaList SingleWhitespaceTrivia;
protected readonly SyntaxTriviaList NoTrivia;
/// <summary>
/// The contents of the documents we've created code-actions for. This is used so that
/// we can prevent creating multiple code actions that produce the same results.
/// </summary>
private readonly List<SyntaxNode> _seenDocumentRoots = new();
public AbstractCodeActionComputer(
TWrapper service,
Document document,
SourceText originalSourceText,
DocumentOptionSet options,
CancellationToken cancellationToken)
{
Wrapper = service;
OriginalDocument = document;
OriginalSourceText = originalSourceText;
CancellationToken = cancellationToken;
UseTabs = options.GetOption(FormattingOptions.UseTabs);
TabSize = options.GetOption(FormattingOptions.TabSize);
NewLine = options.GetOption(FormattingOptions.NewLine);
WrappingColumn = options.GetOption(FormattingOptions2.PreferredWrappingColumn);
var generator = SyntaxGenerator.GetGenerator(document);
var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>();
NewLineTrivia = new SyntaxTriviaList(generatorInternal.EndOfLine(NewLine));
SingleWhitespaceTrivia = new SyntaxTriviaList(generator.Whitespace(" "));
}
protected abstract Task<ImmutableArray<WrappingGroup>> ComputeWrappingGroupsAsync();
protected string GetSmartIndentationAfter(SyntaxNodeOrToken nodeOrToken)
{
var newSourceText = OriginalSourceText.WithChanges(new TextChange(new TextSpan(nodeOrToken.Span.End, 0), NewLine));
newSourceText = newSourceText.WithChanges(
new TextChange(TextSpan.FromBounds(nodeOrToken.Span.End + NewLine.Length, newSourceText.Length), ""));
var newDocument = OriginalDocument.WithText(newSourceText);
var indentationService = Wrapper.IndentationService;
var originalLineNumber = newSourceText.Lines.GetLineFromPosition(nodeOrToken.Span.End).LineNumber;
var desiredIndentation = indentationService.GetIndentation(
newDocument, originalLineNumber + 1,
FormattingOptions.IndentStyle.Smart,
CancellationToken);
var baseLine = newSourceText.Lines.GetLineFromPosition(desiredIndentation.BasePosition);
var baseOffsetInLine = desiredIndentation.BasePosition - baseLine.Start;
var indent = baseOffsetInLine + desiredIndentation.Offset;
var indentString = indent.CreateIndentationString(UseTabs, TabSize);
return indentString;
}
/// <summary>
/// Try to create a CodeAction representing these edits. Can return <see langword="null"/> in several
/// cases, including:
///
/// 1. No edits.
/// 2. Edits would change more than whitespace.
/// 3. A previous code action was created that already had the same effect.
/// </summary>
protected async Task<WrapItemsAction> TryCreateCodeActionAsync(
ImmutableArray<Edit> edits, string parentTitle, string title)
{
// First, rewrite the tree with the edits provided.
var (root, rewrittenRoot, spanToFormat) = await RewriteTreeAsync(edits).ConfigureAwait(false);
if (rewrittenRoot == null)
{
// Couldn't rewrite for some reason. No code action to create.
return null;
}
// Now, format the part of the tree that we edited. This will ensure we properly
// respect the user preferences around things like comma/operator spacing.
var formattedDocument = await FormatDocumentAsync(rewrittenRoot, spanToFormat).ConfigureAwait(false);
var formattedRoot = await formattedDocument.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false);
// Now, check if this new formatted tree matches our starting tree, or any of the
// trees we've already created for our other code actions. If so, we don't want to
// add this duplicative code action. Note: this check will actually run quickly.
// 'IsEquivalentTo' can return quickly when comparing equivalent green nodes. So
// all that we need to check is the spine of the change which will happen very
// quickly.
if (root.IsEquivalentTo(formattedRoot))
{
return null;
}
foreach (var seenRoot in _seenDocumentRoots)
{
if (seenRoot.IsEquivalentTo(formattedRoot))
{
return null;
}
}
// This is a genuinely different code action from all previous ones we've created.
// Store the root so we don't just end up creating this code action again.
_seenDocumentRoots.Add(formattedRoot);
return new WrapItemsAction(title, parentTitle, _ => Task.FromResult(formattedDocument));
}
private async Task<Document> FormatDocumentAsync(SyntaxNode rewrittenRoot, TextSpan spanToFormat)
{
var newDocument = OriginalDocument.WithSyntaxRoot(rewrittenRoot);
var formattedDocument = await Formatter.FormatAsync(
newDocument, spanToFormat, cancellationToken: CancellationToken).ConfigureAwait(false);
return formattedDocument;
}
private async Task<(SyntaxNode root, SyntaxNode rewrittenRoot, TextSpan spanToFormat)> RewriteTreeAsync(ImmutableArray<Edit> edits)
{
using var _1 = PooledDictionary<SyntaxToken, SyntaxTriviaList>.GetInstance(out var leftTokenToTrailingTrivia);
using var _2 = PooledDictionary<SyntaxToken, SyntaxTriviaList>.GetInstance(out var rightTokenToLeadingTrivia);
foreach (var edit in edits)
{
var span = TextSpan.FromBounds(edit.Left.Span.End, edit.Right.Span.Start);
var text = OriginalSourceText.ToString(span);
if (!IsSafeToRemove(text))
{
// editing some piece of non-whitespace trivia. We don't support this.
return default;
}
// Make sure we're not about to make an edit that just changes the code to what
// is already there.
if (text != edit.GetNewTrivia())
{
leftTokenToTrailingTrivia.Add(edit.Left, edit.NewLeftTrailingTrivia);
rightTokenToLeadingTrivia.Add(edit.Right, edit.NewRightLeadingTrivia);
}
}
if (leftTokenToTrailingTrivia.Count == 0)
{
// No actual edits that would change anything. Nothing to do.
return default;
}
return await RewriteTreeAsync(
leftTokenToTrailingTrivia, rightTokenToLeadingTrivia).ConfigureAwait(false);
}
private static bool IsSafeToRemove(string text)
{
foreach (var ch in text)
{
// It's safe to remove whitespace between tokens, or the VB line-continuation character.
if (!char.IsWhiteSpace(ch) && ch != '_')
{
return false;
}
}
return true;
}
private async Task<(SyntaxNode root, SyntaxNode rewrittenRoot, TextSpan spanToFormat)> RewriteTreeAsync(
Dictionary<SyntaxToken, SyntaxTriviaList> leftTokenToTrailingTrivia,
Dictionary<SyntaxToken, SyntaxTriviaList> rightTokenToLeadingTrivia)
{
var root = await OriginalDocument.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false);
var tokens = leftTokenToTrailingTrivia.Keys.Concat(rightTokenToLeadingTrivia.Keys).Distinct().ToImmutableArray();
// Find the closest node that contains all the tokens we're editing. That's the
// node we'll format at the end. This will ensure that all formattin respects
// user settings for things like spacing around commas/operators/etc.
var nodeToFormat = tokens.SelectAsArray(t => t.Parent).FindInnermostCommonNode<SyntaxNode>();
// Rewrite the tree performing the following actions:
//
// 1. Add an annotation to nodeToFormat so that we can find that node again after
// updating all tokens.
//
// 2. Hit all tokens in the two passed in maps, and update their leading/trailing
// trivia accordingly.
var rewrittenRoot = root.ReplaceSyntax(
nodes: new[] { nodeToFormat },
computeReplacementNode: (oldNode, newNode) => newNode.WithAdditionalAnnotations(s_toFormatAnnotation),
tokens: leftTokenToTrailingTrivia.Keys.Concat(rightTokenToLeadingTrivia.Keys).Distinct(),
computeReplacementToken: (oldToken, newToken) =>
{
if (leftTokenToTrailingTrivia.TryGetValue(oldToken, out var trailingTrivia))
{
newToken = newToken.WithTrailingTrivia(trailingTrivia);
}
if (rightTokenToLeadingTrivia.TryGetValue(oldToken, out var leadingTrivia))
{
newToken = newToken.WithLeadingTrivia(leadingTrivia);
}
return newToken;
},
trivia: null,
computeReplacementTrivia: null);
var trackedNode = rewrittenRoot.GetAnnotatedNodes(s_toFormatAnnotation).Single();
return (root, rewrittenRoot, trackedNode.Span);
}
public async Task<ImmutableArray<CodeAction>> GetTopLevelCodeActionsAsync()
{
// Ask subclass to produce whole nested list of wrapping code actions
var wrappingGroups = await ComputeWrappingGroupsAsync().ConfigureAwait(false);
var result = ArrayBuilder<CodeAction>.GetInstance();
foreach (var group in wrappingGroups)
{
// if a group is empty just ignore it.
var wrappingActions = group.WrappingActions.WhereNotNull().ToImmutableArray();
if (wrappingActions.Length == 0)
{
continue;
}
// If a group only has one item, and subclass says the item is inlinable,
// then just directly return that nested item as a top level item.
if (wrappingActions.Length == 1 && group.IsInlinable)
{
result.Add(wrappingActions[0]);
continue;
}
// Otherwise, sort items and add to the resultant list
var sorted = WrapItemsAction.SortActionsByMostRecentlyUsed(ImmutableArray<CodeAction>.CastUp(wrappingActions));
// Make our code action low priority. This option will be offered *a lot*, and
// much of the time will not be something the user particularly wants to do.
// It should be offered after all other normal refactorings.
result.Add(new CodeActionWithNestedActions(
wrappingActions[0].ParentTitle, sorted,
group.IsInlinable, CodeActionPriority.Low));
}
// Finally, sort the topmost list we're building and return that. This ensures that
// both the top level items and the nested items are ordered appropriate.
return WrapItemsAction.SortActionsByMostRecentlyUsed(result.ToImmutableAndFree());
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Features/Core/Portable/FindUsages/DefinitionItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tags;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindUsages
{
/// <summary>
/// Information about a symbol's definition that can be displayed in an editor
/// and used for navigation.
///
/// Standard implmentations can be obtained through the various <see cref="DefinitionItem"/>.Create
/// overloads.
///
/// Subclassing is also supported for scenarios that fall outside the bounds of
/// these common cases.
/// </summary>
internal abstract partial class DefinitionItem
{
/// <summary>
/// The definition item corresponding to the initial symbol the user was trying to find. This item should get
/// prominent placement in the final UI for the user.
/// </summary>
internal const string Primary = nameof(Primary);
// Existing behavior is to do up to two lookups for 3rd party navigation for FAR. One
// for the symbol itself and one for a 'fallback' symbol. For example, if we're FARing
// on a constructor, then the fallback symbol will be the actual type that the constructor
// is contained within.
internal const string RQNameKey1 = nameof(RQNameKey1);
internal const string RQNameKey2 = nameof(RQNameKey2);
/// <summary>
/// For metadata symbols we encode information in the <see cref="Properties"/> so we can
/// retrieve the symbol later on when navigating. This is needed so that we can go to
/// metadata-as-source for metadata symbols. We need to store the <see cref="SymbolKey"/>
/// for the symbol and the project ID that originated the symbol. With these we can correctly recover the symbol.
/// </summary>
private const string MetadataSymbolKey = nameof(MetadataSymbolKey);
private const string MetadataSymbolOriginatingProjectIdGuid = nameof(MetadataSymbolOriginatingProjectIdGuid);
private const string MetadataSymbolOriginatingProjectIdDebugName = nameof(MetadataSymbolOriginatingProjectIdDebugName);
/// <summary>
/// If this item is something that cannot be navigated to. We store this in our
/// <see cref="Properties"/> to act as an explicit marker that navigation is not possible.
/// </summary>
private const string NonNavigable = nameof(NonNavigable);
/// <summary>
/// Descriptive tags from <see cref="WellKnownTags"/>. These tags may influence how the
/// item is displayed.
/// </summary>
public ImmutableArray<string> Tags { get; }
/// <summary>
/// Additional properties that can be attached to the definition for clients that want to
/// keep track of additional data.
/// </summary>
public ImmutableDictionary<string, string> Properties { get; }
/// <summary>
/// Additional diplayable properties that can be attached to the definition for clients that want to
/// display additional data.
/// </summary>
public ImmutableDictionary<string, string> DisplayableProperties { get; }
/// <summary>
/// The DisplayParts just for the name of this definition. Generally used only for
/// error messages.
/// </summary>
public ImmutableArray<TaggedText> NameDisplayParts { get; }
/// <summary>
/// The full display parts for this definition. Displayed in a classified
/// manner when possible.
/// </summary>
public ImmutableArray<TaggedText> DisplayParts { get; }
/// <summary>
/// Where the location originally came from (for example, the containing assembly or
/// project name). May be used in the presentation of a definition.
/// </summary>
public ImmutableArray<TaggedText> OriginationParts { get; }
/// <summary>
/// Additional locations to present in the UI. A definition may have multiple locations
/// for cases like partial types/members.
/// </summary>
public ImmutableArray<DocumentSpan> SourceSpans { get; }
/// <summary>
/// Whether or not this definition should be presented if we never found any references to
/// it. For example, when searching for a property, the FindReferences engine will cascade
/// to the accessors in case any code specifically called those accessors (can happen in
/// cross-language cases). However, in the normal case where there were no calls specifically
/// to the accessor, we would not want to display them in the UI.
///
/// For most definitions we will want to display them, even if no references were found.
/// This property allows for this customization in behavior.
/// </summary>
public bool DisplayIfNoReferences { get; }
internal abstract bool IsExternal { get; }
// F# uses this
protected DefinitionItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
ImmutableArray<TaggedText> originationParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableDictionary<string, string> properties,
bool displayIfNoReferences)
: this(
tags,
displayParts,
nameDisplayParts,
originationParts,
sourceSpans,
properties,
ImmutableDictionary<string, string>.Empty,
displayIfNoReferences)
{
}
protected DefinitionItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
ImmutableArray<TaggedText> originationParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableDictionary<string, string> properties,
ImmutableDictionary<string, string> displayableProperties,
bool displayIfNoReferences)
{
Tags = tags;
DisplayParts = displayParts;
NameDisplayParts = nameDisplayParts.IsDefaultOrEmpty ? displayParts : nameDisplayParts;
OriginationParts = originationParts.NullToEmpty();
SourceSpans = sourceSpans.NullToEmpty();
Properties = properties ?? ImmutableDictionary<string, string>.Empty;
DisplayableProperties = displayableProperties ?? ImmutableDictionary<string, string>.Empty;
DisplayIfNoReferences = displayIfNoReferences;
if (Properties.ContainsKey(MetadataSymbolKey))
{
Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdGuid));
Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdDebugName));
}
}
[Obsolete("Override CanNavigateToAsync instead", error: false)]
public abstract bool CanNavigateTo(Workspace workspace, CancellationToken cancellationToken);
[Obsolete("Override TryNavigateToAsync instead", error: false)]
public abstract bool TryNavigateTo(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken);
public virtual Task<bool> CanNavigateToAsync(Workspace workspace, CancellationToken cancellationToken)
{
#pragma warning disable CS0618 // Type or member is obsolete
return Task.FromResult(CanNavigateTo(workspace, cancellationToken));
#pragma warning restore CS0618 // Type or member is obsolete
}
public virtual Task<bool> TryNavigateToAsync(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken)
{
#pragma warning disable CS0618 // Type or member is obsolete
return Task.FromResult(TryNavigateTo(workspace, showInPreviewTab, activateTab, cancellationToken));
#pragma warning restore CS0618 // Type or member is obsolete
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
DocumentSpan sourceSpan,
ImmutableArray<TaggedText> nameDisplayParts = default,
bool displayIfNoReferences = true)
{
return Create(
tags, displayParts, ImmutableArray.Create(sourceSpan),
nameDisplayParts, displayIfNoReferences);
}
// Kept around for binary compat with F#/TypeScript.
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts,
bool displayIfNoReferences)
{
return Create(
tags, displayParts, sourceSpans, nameDisplayParts,
properties: null, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences);
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts = default,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
return Create(tags, displayParts, sourceSpans, nameDisplayParts, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences);
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts = default,
ImmutableDictionary<string, string> properties = null,
ImmutableDictionary<string, string> displayableProperties = null,
bool displayIfNoReferences = true)
{
if (sourceSpans.Length == 0)
{
throw new ArgumentException($"{nameof(sourceSpans)} cannot be empty.");
}
var firstDocument = sourceSpans[0].Document;
var originationParts = ImmutableArray.Create(
new TaggedText(TextTags.Text, firstDocument.Project.Name));
return new DefaultDefinitionItem(
tags, displayParts, nameDisplayParts, originationParts,
sourceSpans, properties, displayableProperties, displayIfNoReferences);
}
internal static DefinitionItem CreateMetadataDefinition(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
Solution solution,
ISymbol symbol,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
properties ??= ImmutableDictionary<string, string>.Empty;
var symbolKey = symbol.GetSymbolKey().ToString();
var projectId = solution.GetOriginatingProjectId(symbol);
Contract.ThrowIfNull(projectId);
properties = properties.Add(MetadataSymbolKey, symbolKey)
.Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString())
.Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName);
var originationParts = GetOriginationParts(symbol);
return new DefaultDefinitionItem(
tags, displayParts, nameDisplayParts, originationParts,
sourceSpans: ImmutableArray<DocumentSpan>.Empty,
properties: properties,
displayableProperties: ImmutableDictionary<string, string>.Empty,
displayIfNoReferences: displayIfNoReferences);
}
// Kept around for binary compat with F#/TypeScript.
public static DefinitionItem CreateNonNavigableItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> originationParts,
bool displayIfNoReferences)
{
return CreateNonNavigableItem(
tags, displayParts, originationParts,
properties: null, displayIfNoReferences: displayIfNoReferences);
}
public static DefinitionItem CreateNonNavigableItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> originationParts = default,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
properties ??= ImmutableDictionary<string, string>.Empty;
properties = properties.Add(NonNavigable, "");
return new DefaultDefinitionItem(
tags: tags,
displayParts: displayParts,
nameDisplayParts: ImmutableArray<TaggedText>.Empty,
originationParts: originationParts,
sourceSpans: ImmutableArray<DocumentSpan>.Empty,
properties: properties,
displayableProperties: ImmutableDictionary<string, string>.Empty,
displayIfNoReferences: displayIfNoReferences);
}
internal static ImmutableArray<TaggedText> GetOriginationParts(ISymbol symbol)
{
// We don't show an origination location for a namespace because it can span over
// both metadata assemblies and source projects.
//
// Otherwise show the assembly this symbol came from as the Origination of
// the DefinitionItem.
if (symbol.Kind != SymbolKind.Namespace)
{
var assemblyName = symbol.ContainingAssembly?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
if (!string.IsNullOrWhiteSpace(assemblyName))
{
return ImmutableArray.Create(new TaggedText(TextTags.Assembly, assemblyName));
}
}
return ImmutableArray<TaggedText>.Empty;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tags;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindUsages
{
/// <summary>
/// Information about a symbol's definition that can be displayed in an editor
/// and used for navigation.
///
/// Standard implmentations can be obtained through the various <see cref="DefinitionItem"/>.Create
/// overloads.
///
/// Subclassing is also supported for scenarios that fall outside the bounds of
/// these common cases.
/// </summary>
internal abstract partial class DefinitionItem
{
/// <summary>
/// The definition item corresponding to the initial symbol the user was trying to find. This item should get
/// prominent placement in the final UI for the user.
/// </summary>
internal const string Primary = nameof(Primary);
// Existing behavior is to do up to two lookups for 3rd party navigation for FAR. One
// for the symbol itself and one for a 'fallback' symbol. For example, if we're FARing
// on a constructor, then the fallback symbol will be the actual type that the constructor
// is contained within.
internal const string RQNameKey1 = nameof(RQNameKey1);
internal const string RQNameKey2 = nameof(RQNameKey2);
/// <summary>
/// For metadata symbols we encode information in the <see cref="Properties"/> so we can
/// retrieve the symbol later on when navigating. This is needed so that we can go to
/// metadata-as-source for metadata symbols. We need to store the <see cref="SymbolKey"/>
/// for the symbol and the project ID that originated the symbol. With these we can correctly recover the symbol.
/// </summary>
private const string MetadataSymbolKey = nameof(MetadataSymbolKey);
private const string MetadataSymbolOriginatingProjectIdGuid = nameof(MetadataSymbolOriginatingProjectIdGuid);
private const string MetadataSymbolOriginatingProjectIdDebugName = nameof(MetadataSymbolOriginatingProjectIdDebugName);
/// <summary>
/// If this item is something that cannot be navigated to. We store this in our
/// <see cref="Properties"/> to act as an explicit marker that navigation is not possible.
/// </summary>
private const string NonNavigable = nameof(NonNavigable);
/// <summary>
/// Descriptive tags from <see cref="WellKnownTags"/>. These tags may influence how the
/// item is displayed.
/// </summary>
public ImmutableArray<string> Tags { get; }
/// <summary>
/// Additional properties that can be attached to the definition for clients that want to
/// keep track of additional data.
/// </summary>
public ImmutableDictionary<string, string> Properties { get; }
/// <summary>
/// Additional diplayable properties that can be attached to the definition for clients that want to
/// display additional data.
/// </summary>
public ImmutableDictionary<string, string> DisplayableProperties { get; }
/// <summary>
/// The DisplayParts just for the name of this definition. Generally used only for
/// error messages.
/// </summary>
public ImmutableArray<TaggedText> NameDisplayParts { get; }
/// <summary>
/// The full display parts for this definition. Displayed in a classified
/// manner when possible.
/// </summary>
public ImmutableArray<TaggedText> DisplayParts { get; }
/// <summary>
/// Where the location originally came from (for example, the containing assembly or
/// project name). May be used in the presentation of a definition.
/// </summary>
public ImmutableArray<TaggedText> OriginationParts { get; }
/// <summary>
/// Additional locations to present in the UI. A definition may have multiple locations
/// for cases like partial types/members.
/// </summary>
public ImmutableArray<DocumentSpan> SourceSpans { get; }
/// <summary>
/// Whether or not this definition should be presented if we never found any references to
/// it. For example, when searching for a property, the FindReferences engine will cascade
/// to the accessors in case any code specifically called those accessors (can happen in
/// cross-language cases). However, in the normal case where there were no calls specifically
/// to the accessor, we would not want to display them in the UI.
///
/// For most definitions we will want to display them, even if no references were found.
/// This property allows for this customization in behavior.
/// </summary>
public bool DisplayIfNoReferences { get; }
internal abstract bool IsExternal { get; }
// F# uses this
protected DefinitionItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
ImmutableArray<TaggedText> originationParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableDictionary<string, string> properties,
bool displayIfNoReferences)
: this(
tags,
displayParts,
nameDisplayParts,
originationParts,
sourceSpans,
properties,
ImmutableDictionary<string, string>.Empty,
displayIfNoReferences)
{
}
protected DefinitionItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
ImmutableArray<TaggedText> originationParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableDictionary<string, string> properties,
ImmutableDictionary<string, string> displayableProperties,
bool displayIfNoReferences)
{
Tags = tags;
DisplayParts = displayParts;
NameDisplayParts = nameDisplayParts.IsDefaultOrEmpty ? displayParts : nameDisplayParts;
OriginationParts = originationParts.NullToEmpty();
SourceSpans = sourceSpans.NullToEmpty();
Properties = properties ?? ImmutableDictionary<string, string>.Empty;
DisplayableProperties = displayableProperties ?? ImmutableDictionary<string, string>.Empty;
DisplayIfNoReferences = displayIfNoReferences;
if (Properties.ContainsKey(MetadataSymbolKey))
{
Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdGuid));
Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdDebugName));
}
}
[Obsolete("Override CanNavigateToAsync instead", error: false)]
public abstract bool CanNavigateTo(Workspace workspace, CancellationToken cancellationToken);
[Obsolete("Override TryNavigateToAsync instead", error: false)]
public abstract bool TryNavigateTo(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken);
public virtual Task<bool> CanNavigateToAsync(Workspace workspace, CancellationToken cancellationToken)
{
#pragma warning disable CS0618 // Type or member is obsolete
return Task.FromResult(CanNavigateTo(workspace, cancellationToken));
#pragma warning restore CS0618 // Type or member is obsolete
}
public virtual Task<bool> TryNavigateToAsync(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken)
{
#pragma warning disable CS0618 // Type or member is obsolete
return Task.FromResult(TryNavigateTo(workspace, showInPreviewTab, activateTab, cancellationToken));
#pragma warning restore CS0618 // Type or member is obsolete
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
DocumentSpan sourceSpan,
ImmutableArray<TaggedText> nameDisplayParts = default,
bool displayIfNoReferences = true)
{
return Create(
tags, displayParts, ImmutableArray.Create(sourceSpan),
nameDisplayParts, displayIfNoReferences);
}
// Kept around for binary compat with F#/TypeScript.
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts,
bool displayIfNoReferences)
{
return Create(
tags, displayParts, sourceSpans, nameDisplayParts,
properties: null, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences);
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts = default,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
return Create(tags, displayParts, sourceSpans, nameDisplayParts, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences);
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts = default,
ImmutableDictionary<string, string> properties = null,
ImmutableDictionary<string, string> displayableProperties = null,
bool displayIfNoReferences = true)
{
if (sourceSpans.Length == 0)
{
throw new ArgumentException($"{nameof(sourceSpans)} cannot be empty.");
}
var firstDocument = sourceSpans[0].Document;
var originationParts = ImmutableArray.Create(
new TaggedText(TextTags.Text, firstDocument.Project.Name));
return new DefaultDefinitionItem(
tags, displayParts, nameDisplayParts, originationParts,
sourceSpans, properties, displayableProperties, displayIfNoReferences);
}
internal static DefinitionItem CreateMetadataDefinition(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
Solution solution,
ISymbol symbol,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
properties ??= ImmutableDictionary<string, string>.Empty;
var symbolKey = symbol.GetSymbolKey().ToString();
var projectId = solution.GetOriginatingProjectId(symbol);
Contract.ThrowIfNull(projectId);
properties = properties.Add(MetadataSymbolKey, symbolKey)
.Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString())
.Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName);
var originationParts = GetOriginationParts(symbol);
return new DefaultDefinitionItem(
tags, displayParts, nameDisplayParts, originationParts,
sourceSpans: ImmutableArray<DocumentSpan>.Empty,
properties: properties,
displayableProperties: ImmutableDictionary<string, string>.Empty,
displayIfNoReferences: displayIfNoReferences);
}
// Kept around for binary compat with F#/TypeScript.
public static DefinitionItem CreateNonNavigableItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> originationParts,
bool displayIfNoReferences)
{
return CreateNonNavigableItem(
tags, displayParts, originationParts,
properties: null, displayIfNoReferences: displayIfNoReferences);
}
public static DefinitionItem CreateNonNavigableItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> originationParts = default,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
properties ??= ImmutableDictionary<string, string>.Empty;
properties = properties.Add(NonNavigable, "");
return new DefaultDefinitionItem(
tags: tags,
displayParts: displayParts,
nameDisplayParts: ImmutableArray<TaggedText>.Empty,
originationParts: originationParts,
sourceSpans: ImmutableArray<DocumentSpan>.Empty,
properties: properties,
displayableProperties: ImmutableDictionary<string, string>.Empty,
displayIfNoReferences: displayIfNoReferences);
}
internal static ImmutableArray<TaggedText> GetOriginationParts(ISymbol symbol)
{
// We don't show an origination location for a namespace because it can span over
// both metadata assemblies and source projects.
//
// Otherwise show the assembly this symbol came from as the Origination of
// the DefinitionItem.
if (symbol.Kind != SymbolKind.Namespace)
{
var assemblyName = symbol.ContainingAssembly?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
if (!string.IsNullOrWhiteSpace(assemblyName))
{
return ImmutableArray.Create(new TaggedText(TextTags.Assembly, assemblyName));
}
}
return ImmutableArray<TaggedText>.Empty;
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Analyzers/CSharp/CodeFixes/UseObjectInitializer/UseInitializerHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.UseObjectInitializer
{
internal static class UseInitializerHelpers
{
public static ObjectCreationExpressionSyntax GetNewObjectCreation(
ObjectCreationExpressionSyntax objectCreation,
SeparatedSyntaxList<ExpressionSyntax> expressions)
{
var openBrace = SyntaxFactory.Token(SyntaxKind.OpenBraceToken)
.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
var initializer = SyntaxFactory.InitializerExpression(
SyntaxKind.ObjectInitializerExpression, expressions).WithOpenBraceToken(openBrace);
if (objectCreation.ArgumentList != null &&
objectCreation.ArgumentList.Arguments.Count == 0)
{
objectCreation = objectCreation.WithType(objectCreation.Type.WithTrailingTrivia(objectCreation.ArgumentList.GetTrailingTrivia()))
.WithArgumentList(null);
}
return objectCreation.WithInitializer(initializer);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.UseObjectInitializer
{
internal static class UseInitializerHelpers
{
public static ObjectCreationExpressionSyntax GetNewObjectCreation(
ObjectCreationExpressionSyntax objectCreation,
SeparatedSyntaxList<ExpressionSyntax> expressions)
{
var openBrace = SyntaxFactory.Token(SyntaxKind.OpenBraceToken)
.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
var initializer = SyntaxFactory.InitializerExpression(
SyntaxKind.ObjectInitializerExpression, expressions).WithOpenBraceToken(openBrace);
if (objectCreation.ArgumentList != null &&
objectCreation.ArgumentList.Arguments.Count == 0)
{
objectCreation = objectCreation.WithType(objectCreation.Type.WithTrailingTrivia(objectCreation.ArgumentList.GetTrailingTrivia()))
.WithArgumentList(null);
}
return objectCreation.WithInitializer(initializer);
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.PropertyAccessorSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed partial class AnonymousTypeManager
{
/// <summary>
/// Represents a getter for anonymous type property.
/// </summary>
private sealed partial class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase
{
private readonly AnonymousTypePropertySymbol _property;
internal AnonymousTypePropertyGetAccessorSymbol(AnonymousTypePropertySymbol property)
// winmdobj output only effects setters, so we can always set this to false
: base(property.ContainingType, SourcePropertyAccessorSymbol.GetAccessorName(property.Name, getNotSet: true, isWinMdOutput: false))
{
_property = property;
}
public override MethodKind MethodKind
{
get { return MethodKind.PropertyGet; }
}
public override bool ReturnsVoid
{
get { return false; }
}
public override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeWithAnnotations ReturnTypeWithAnnotations
{
get { return _property.TypeWithAnnotations; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return ImmutableArray<ParameterSymbol>.Empty; }
}
public override Symbol AssociatedSymbol
{
get { return _property; }
}
public override ImmutableArray<Location> Locations
{
get
{
// The accessor for a anonymous type property has the same location as the property.
return _property.Locations;
}
}
public override bool IsOverride
{
get { return false; }
}
internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
// Do not call base.AddSynthesizedAttributes.
// Dev11 does not emit DebuggerHiddenAttribute in property accessors
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed partial class AnonymousTypeManager
{
/// <summary>
/// Represents a getter for anonymous type property.
/// </summary>
private sealed partial class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase
{
private readonly AnonymousTypePropertySymbol _property;
internal AnonymousTypePropertyGetAccessorSymbol(AnonymousTypePropertySymbol property)
// winmdobj output only effects setters, so we can always set this to false
: base(property.ContainingType, SourcePropertyAccessorSymbol.GetAccessorName(property.Name, getNotSet: true, isWinMdOutput: false))
{
_property = property;
}
public override MethodKind MethodKind
{
get { return MethodKind.PropertyGet; }
}
public override bool ReturnsVoid
{
get { return false; }
}
public override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeWithAnnotations ReturnTypeWithAnnotations
{
get { return _property.TypeWithAnnotations; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return ImmutableArray<ParameterSymbol>.Empty; }
}
public override Symbol AssociatedSymbol
{
get { return _property; }
}
public override ImmutableArray<Location> Locations
{
get
{
// The accessor for a anonymous type property has the same location as the property.
return _property.Locations;
}
}
public override bool IsOverride
{
get { return false; }
}
internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
// Do not call base.AddSynthesizedAttributes.
// Dev11 does not emit DebuggerHiddenAttribute in property accessors
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Tools/ExternalAccess/FSharp/Internal/FSharpContentTypeDefinitions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal
{
internal static class FSharpContentTypeDefinitions
{
[Export]
[Name(FSharpContentTypeNames.FSharpContentType)]
[BaseDefinition(FSharpContentTypeNames.RoslynContentType)]
[BaseDefinition(CodeRemoteContentDefinition.CodeRemoteBaseTypeName)]
public static readonly ContentTypeDefinition FSharpContentTypeDefinition;
[Export]
[Name(FSharpContentTypeNames.FSharpSignatureHelpContentType)]
[BaseDefinition("sighelp")]
public static readonly ContentTypeDefinition FSharpSignatureHelpContentTypeDefinition;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal
{
internal static class FSharpContentTypeDefinitions
{
[Export]
[Name(FSharpContentTypeNames.FSharpContentType)]
[BaseDefinition(FSharpContentTypeNames.RoslynContentType)]
[BaseDefinition(CodeRemoteContentDefinition.CodeRemoteBaseTypeName)]
public static readonly ContentTypeDefinition FSharpContentTypeDefinition;
[Export]
[Name(FSharpContentTypeNames.FSharpSignatureHelpContentType)]
[BaseDefinition("sighelp")]
public static readonly ContentTypeDefinition FSharpSignatureHelpContentTypeDefinition;
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/CSharp/Portable/Syntax/ExpressionStatementSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class ExpressionStatementSyntax
{
/// <summary>
/// Returns true if the <see cref="Expression"/> property is allowed by the rules of the
/// language to be an arbitrary expression, not just a statement expression.
/// </summary>
/// <remarks>
/// True if, for example, this expression statement represents the last expression statement
/// of the interactive top-level code.
/// </remarks>
public bool AllowsAnyExpression
{
get
{
var semicolon = SemicolonToken;
return semicolon.IsMissing && !semicolon.ContainsDiagnostics;
}
}
public ExpressionStatementSyntax Update(ExpressionSyntax expression, SyntaxToken semicolonToken)
=> Update(AttributeLists, expression, semicolonToken);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static ExpressionStatementSyntax ExpressionStatement(ExpressionSyntax expression, SyntaxToken semicolonToken)
=> ExpressionStatement(attributeLists: default, expression, 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.
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class ExpressionStatementSyntax
{
/// <summary>
/// Returns true if the <see cref="Expression"/> property is allowed by the rules of the
/// language to be an arbitrary expression, not just a statement expression.
/// </summary>
/// <remarks>
/// True if, for example, this expression statement represents the last expression statement
/// of the interactive top-level code.
/// </remarks>
public bool AllowsAnyExpression
{
get
{
var semicolon = SemicolonToken;
return semicolon.IsMissing && !semicolon.ContainsDiagnostics;
}
}
public ExpressionStatementSyntax Update(ExpressionSyntax expression, SyntaxToken semicolonToken)
=> Update(AttributeLists, expression, semicolonToken);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static ExpressionStatementSyntax ExpressionStatement(ExpressionSyntax expression, SyntaxToken semicolonToken)
=> ExpressionStatement(attributeLists: default, expression, semicolonToken);
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordObjectMethod.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Common base for ordinary methods overriding methods from object synthesized by compiler for records.
/// </summary>
internal abstract class SynthesizedRecordObjectMethod : SynthesizedRecordOrdinaryMethod
{
protected SynthesizedRecordObjectMethod(SourceMemberContainerTypeSymbol containingType, string name, int memberOffset, bool isReadOnly, BindingDiagnosticBag diagnostics)
: base(containingType, name, isReadOnly: isReadOnly, hasBody: true, memberOffset, diagnostics)
{
}
protected sealed override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics)
{
const DeclarationModifiers result = DeclarationModifiers.Public | DeclarationModifiers.Override;
Debug.Assert((result & ~allowedModifiers) == 0);
return result;
}
protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics)
{
base.MethodChecks(diagnostics);
VerifyOverridesMethodFromObject(this, OverriddenSpecialMember, diagnostics);
}
protected abstract SpecialMember OverriddenSpecialMember { get; }
/// <summary>
/// Returns true if reported an error
/// </summary>
internal static bool VerifyOverridesMethodFromObject(MethodSymbol overriding, SpecialMember overriddenSpecialMember, BindingDiagnosticBag diagnostics)
{
bool reportAnError = false;
if (!overriding.IsOverride)
{
reportAnError = true;
}
else
{
var overridden = overriding.OverriddenMethod?.OriginalDefinition;
if (overridden is object && !(overridden.ContainingType is SourceMemberContainerTypeSymbol { IsRecord: true } && overridden.ContainingModule == overriding.ContainingModule))
{
MethodSymbol leastOverridden = overriding.GetLeastOverriddenMethod(accessingTypeOpt: null);
reportAnError = (object)leastOverridden != overriding.ContainingAssembly.GetSpecialTypeMember(overriddenSpecialMember) &&
leastOverridden.ReturnType.Equals(overriding.ReturnType, TypeCompareKind.AllIgnoreOptions);
}
}
if (reportAnError)
{
diagnostics.Add(ErrorCode.ERR_DoesNotOverrideMethodFromObject, overriding.Locations[0], overriding);
}
return reportAnError;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Common base for ordinary methods overriding methods from object synthesized by compiler for records.
/// </summary>
internal abstract class SynthesizedRecordObjectMethod : SynthesizedRecordOrdinaryMethod
{
protected SynthesizedRecordObjectMethod(SourceMemberContainerTypeSymbol containingType, string name, int memberOffset, bool isReadOnly, BindingDiagnosticBag diagnostics)
: base(containingType, name, isReadOnly: isReadOnly, hasBody: true, memberOffset, diagnostics)
{
}
protected sealed override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics)
{
const DeclarationModifiers result = DeclarationModifiers.Public | DeclarationModifiers.Override;
Debug.Assert((result & ~allowedModifiers) == 0);
return result;
}
protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics)
{
base.MethodChecks(diagnostics);
VerifyOverridesMethodFromObject(this, OverriddenSpecialMember, diagnostics);
}
protected abstract SpecialMember OverriddenSpecialMember { get; }
/// <summary>
/// Returns true if reported an error
/// </summary>
internal static bool VerifyOverridesMethodFromObject(MethodSymbol overriding, SpecialMember overriddenSpecialMember, BindingDiagnosticBag diagnostics)
{
bool reportAnError = false;
if (!overriding.IsOverride)
{
reportAnError = true;
}
else
{
var overridden = overriding.OverriddenMethod?.OriginalDefinition;
if (overridden is object && !(overridden.ContainingType is SourceMemberContainerTypeSymbol { IsRecord: true } && overridden.ContainingModule == overriding.ContainingModule))
{
MethodSymbol leastOverridden = overriding.GetLeastOverriddenMethod(accessingTypeOpt: null);
reportAnError = (object)leastOverridden != overriding.ContainingAssembly.GetSpecialTypeMember(overriddenSpecialMember) &&
leastOverridden.ReturnType.Equals(overriding.ReturnType, TypeCompareKind.AllIgnoreOptions);
}
}
if (reportAnError)
{
diagnostics.Add(ErrorCode.ERR_DoesNotOverrideMethodFromObject, overriding.Locations[0], overriding);
}
return reportAnError;
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Tools/ExternalAccess/FSharp/Internal/VisualStudio/Text/Classification/FSharpSignatureHelpClassifierProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.VisualStudio.Text.Classification
{
[Export(typeof(IClassifierProvider))]
[ContentType(FSharpContentTypeNames.FSharpSignatureHelpContentType)]
internal class FSharpSignatureHelpClassifierProvider : IClassifierProvider
{
private readonly ClassificationTypeMap _typeMap;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpSignatureHelpClassifierProvider(ClassificationTypeMap typeMap)
{
_typeMap = typeMap;
}
public IClassifier GetClassifier(ITextBuffer textBuffer)
{
return new SignatureHelpClassifier(textBuffer, _typeMap);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.VisualStudio.Utilities;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.VisualStudio.Text.Classification
{
[Export(typeof(IClassifierProvider))]
[ContentType(FSharpContentTypeNames.FSharpSignatureHelpContentType)]
internal class FSharpSignatureHelpClassifierProvider : IClassifierProvider
{
private readonly ClassificationTypeMap _typeMap;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpSignatureHelpClassifierProvider(ClassificationTypeMap typeMap)
{
_typeMap = typeMap;
}
public IClassifier GetClassifier(ITextBuffer textBuffer)
{
return new SignatureHelpClassifier(textBuffer, _typeMap);
}
}
}
| -1 |
|
dotnet/roslyn | 56,484 | Fix features using ISyntaxFacts as a place to store C# specific questions | CyrusNajmabadi | "2021-09-17T17:20:18Z" | "2021-09-17T18:54:11Z" | d695369176aa109f0e0fb8b0019294aaa0823a54 | 7fb0d236cdda24e8003f60c0fd32fc2af215027c | Fix features using ISyntaxFacts as a place to store C# specific questions. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Utilities/PossibleDeclarationTypes.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.VisualBasic.Utilities
<Flags()>
Friend Enum PossibleDeclarationTypes As UInteger
Method = 1 << 0
[Class] = 1 << 1
[Structure] = 1 << 2
[Interface] = 1 << 3
[Enum] = 1 << 4
[Delegate] = 1 << 5
[Module] = 1 << 6
AllTypes = [Class] Or [Structure] Or [Interface] Or [Enum] Or [Delegate] Or [Module]
[Operator] = 1 << 7
[Property] = 1 << 8
Field = 1 << 9
[Event] = 1 << 10
ExternalMethod = 1 << 11
ProtectedMember = 1 << 12
OverridableMethod = 1 << 13
Accessor = 1 << 14
IteratorFunction = 1 << 15
IteratorProperty = 1 << 16
End Enum
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.VisualBasic.Utilities
<Flags()>
Friend Enum PossibleDeclarationTypes As UInteger
Method = 1 << 0
[Class] = 1 << 1
[Structure] = 1 << 2
[Interface] = 1 << 3
[Enum] = 1 << 4
[Delegate] = 1 << 5
[Module] = 1 << 6
AllTypes = [Class] Or [Structure] Or [Interface] Or [Enum] Or [Delegate] Or [Module]
[Operator] = 1 << 7
[Property] = 1 << 8
Field = 1 << 9
[Event] = 1 << 10
ExternalMethod = 1 << 11
ProtectedMember = 1 << 12
OverridableMethod = 1 << 13
Accessor = 1 << 14
IteratorFunction = 1 << 15
IteratorProperty = 1 << 16
End Enum
End Namespace
| -1 |