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,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/EditorFeatures/VisualBasicTest/ConvertCast/ConvertTryCastToDirectCastTests.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 VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators.VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertCast
<Trait(Traits.Feature, Traits.Features.ConvertCast)>
Public Class ConvertTryCastToDirectCastTests
<Fact>
Public Async Function ConvertFromTryCastToDirectCast() As Task
Dim markup =
"
Module Program
Sub M()
Dim x = TryCast(1[||], Object)
End Sub
End Module
"
Dim expected =
"
Module Program
Sub M()
Dim x = DirectCast(1, Object)
End Sub
End Module
"
Await New VerifyVB.Test With
{
.TestCode = markup,
.FixedCode = expected
}.RunAsync()
End Function
<Theory>
<InlineData("TryCast(TryCast(1, [||]object), C)",
"TryCast(DirectCast(1, object), C)")>
<InlineData("TryCast(TryCast(1, object), [||]C)",
"DirectCast(TryCast(1, object), C)")>
Public Async Function ConvertFromTryCastNested(DirectCastExpression As String, converted As String) As Task
Dim markup =
"
Public Class C
End Class
Module Program
Sub M()
Dim x = " + DirectCastExpression + "
End Sub
End Module
"
Dim fixed =
"
Public Class C
End Class
Module Program
Sub M()
Dim x = " + converted + "
End Sub
End Module
"
Await New VerifyVB.Test With
{
.TestCode = markup,
.FixedCode = fixed
}.RunAsync()
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 VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeRefactoringVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators.VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertCast
<Trait(Traits.Feature, Traits.Features.ConvertCast)>
Public Class ConvertTryCastToDirectCastTests
<Fact>
Public Async Function ConvertFromTryCastToDirectCast() As Task
Dim markup =
"
Module Program
Sub M()
Dim x = TryCast(1[||], Object)
End Sub
End Module
"
Dim expected =
"
Module Program
Sub M()
Dim x = DirectCast(1, Object)
End Sub
End Module
"
Await New VerifyVB.Test With
{
.TestCode = markup,
.FixedCode = expected
}.RunAsync()
End Function
<Theory>
<InlineData("TryCast(TryCast(1, [||]object), C)",
"TryCast(DirectCast(1, object), C)")>
<InlineData("TryCast(TryCast(1, object), [||]C)",
"DirectCast(TryCast(1, object), C)")>
Public Async Function ConvertFromTryCastNested(DirectCastExpression As String, converted As String) As Task
Dim markup =
"
Public Class C
End Class
Module Program
Sub M()
Dim x = " + DirectCastExpression + "
End Sub
End Module
"
Dim fixed =
"
Public Class C
End Class
Module Program
Sub M()
Dim x = " + converted + "
End Sub
End Module
"
Await New VerifyVB.Test With
{
.TestCode = markup,
.FixedCode = fixed
}.RunAsync()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Workspaces/VisualBasic/Portable/Classification/Worker.DocumentationCommentClassifier.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.Classification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification
Partial Friend Class Worker
Private Class DocumentationCommentClassifier
Private ReadOnly _worker As Worker
Public Sub New(worker As Worker)
_worker = worker
End Sub
Friend Sub Classify(documentationComment As DocumentationCommentTriviaSyntax)
If Not _worker._textSpan.OverlapsWith(documentationComment.Span) Then
Return
End If
For Each xmlNode In documentationComment.Content
Dim childFullSpan = xmlNode.FullSpan
If childFullSpan.Start > _worker._textSpan.End Then
Return
ElseIf childFullSpan.End < _worker._textSpan.Start Then
Continue For
End If
ClassifyXmlNode(xmlNode)
Next
End Sub
Private Sub ClassifyXmlNode(node As XmlNodeSyntax)
If node Is Nothing Then
Return
End If
Select Case node.Kind
Case SyntaxKind.XmlText
ClassifyXmlText(DirectCast(node, XmlTextSyntax))
Case SyntaxKind.XmlElement
ClassifyElement(DirectCast(node, XmlElementSyntax))
Case SyntaxKind.XmlEmptyElement
ClassifyEmptyElement(DirectCast(node, XmlEmptyElementSyntax))
Case SyntaxKind.XmlName
ClassifyXmlName(DirectCast(node, XmlNameSyntax))
Case SyntaxKind.XmlString
ClassifyString(DirectCast(node, XmlStringSyntax))
Case SyntaxKind.XmlComment
ClassifyComment(DirectCast(node, XmlCommentSyntax))
Case SyntaxKind.XmlCDataSection
ClassifyCData(DirectCast(node, XmlCDataSectionSyntax))
Case SyntaxKind.XmlProcessingInstruction
ClassifyProcessingInstruction(DirectCast(node, XmlProcessingInstructionSyntax))
End Select
End Sub
Private Sub ClassifyXmlTrivia(trivialList As SyntaxTriviaList, Optional whitespaceClassificationType As String = Nothing)
For Each t In trivialList
Select Case t.Kind()
Case SyntaxKind.DocumentationCommentExteriorTrivia
ClassifyExteriorTrivia(t)
Case SyntaxKind.WhitespaceTrivia
If whitespaceClassificationType IsNot Nothing Then
_worker.AddClassification(t, whitespaceClassificationType)
End If
End Select
Next
End Sub
Private Sub ClassifyExteriorTrivia(trivia As SyntaxTrivia)
' Note: The exterior trivia can contain whitespace (usually leading) and we want to avoid classifying it.
' PERFORMANCE:
' While the call to SyntaxTrivia.ToString() looks Like an allocation, it isn't.
' The SyntaxTrivia green node holds the string text of the trivia in a field And ToString()
' just returns a reference to that.
Dim text = trivia.ToString()
Dim spanStart As Integer? = Nothing
For index = 0 To text.Length - 1
Dim ch = text(index)
If spanStart IsNot Nothing AndAlso Char.IsWhiteSpace(ch) Then
Dim span = TextSpan.FromBounds(spanStart.Value, spanStart.Value + index)
_worker.AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter)
spanStart = Nothing
ElseIf spanStart Is Nothing AndAlso Not Char.IsWhiteSpace(ch) Then
spanStart = trivia.Span.Start + index
End If
Next
' Add a final classification if we hadn't encountered anymore whitespace at the end
If spanStart IsNot Nothing Then
Dim span = TextSpan.FromBounds(spanStart.Value, trivia.Span.End)
_worker.AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter)
End If
End Sub
Private Sub AddXmlClassification(token As SyntaxToken, classificationType As String)
If token.HasLeadingTrivia Then
ClassifyXmlTrivia(token.LeadingTrivia, classificationType)
End If
_worker.AddClassification(token, classificationType)
If token.HasTrailingTrivia Then
ClassifyXmlTrivia(token.TrailingTrivia, classificationType)
End If
End Sub
Private Sub ClassifyXmlTextTokens(textTokens As SyntaxTokenList)
For Each token In textTokens
If token.HasLeadingTrivia Then
ClassifyXmlTrivia(token.LeadingTrivia, whitespaceClassificationType:=ClassificationTypeNames.XmlDocCommentText)
End If
ClassifyXmlTextToken(token)
If token.HasTrailingTrivia Then
ClassifyXmlTrivia(token.TrailingTrivia, whitespaceClassificationType:=ClassificationTypeNames.XmlDocCommentText)
End If
Next token
End Sub
Private Sub ClassifyXmlTextToken(token As SyntaxToken)
If token.Kind = SyntaxKind.XmlEntityLiteralToken Then
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentEntityReference)
ElseIf token.Kind() <> SyntaxKind.DocumentationCommentLineBreakToken Then
Select Case token.Parent.Kind
Case SyntaxKind.XmlText
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentText)
Case SyntaxKind.XmlString
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentAttributeValue)
Case SyntaxKind.XmlComment
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentComment)
Case SyntaxKind.XmlCDataSection
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentCDataSection)
Case SyntaxKind.XmlProcessingInstruction
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentProcessingInstruction)
End Select
End If
End Sub
Private Sub ClassifyXmlName(node As XmlNameSyntax)
Dim classificationType As String
If TypeOf node.Parent Is BaseXmlAttributeSyntax Then
classificationType = ClassificationTypeNames.XmlDocCommentAttributeName
ElseIf TypeOf node.Parent Is XmlProcessingInstructionSyntax Then
classificationType = ClassificationTypeNames.XmlDocCommentProcessingInstruction
Else
classificationType = ClassificationTypeNames.XmlDocCommentName
End If
Dim prefix = node.Prefix
If prefix IsNot Nothing Then
AddXmlClassification(prefix.Name, classificationType)
AddXmlClassification(prefix.ColonToken, classificationType)
End If
AddXmlClassification(node.LocalName, classificationType)
End Sub
Private Sub ClassifyElement(xmlElementSyntax As XmlElementSyntax)
ClassifyElementStart(xmlElementSyntax.StartTag)
For Each xmlNode In xmlElementSyntax.Content
ClassifyXmlNode(xmlNode)
Next
ClassifyElementEnd(xmlElementSyntax.EndTag)
End Sub
Private Sub ClassifyElementStart(node As XmlElementStartTagSyntax)
AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlNode(node.Name)
' Note: In xml doc comments, attributes can only _be_ attributes.
' there are no expression holes here.
For Each attribute In node.Attributes
ClassifyBaseXmlAttribute(TryCast(attribute, BaseXmlAttributeSyntax))
Next
AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyElementEnd(node As XmlElementEndTagSyntax)
AddXmlClassification(node.LessThanSlashToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlNode(node.Name)
AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyEmptyElement(node As XmlEmptyElementSyntax)
AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlNode(node.Name)
' Note: In xml doc comments, attributes can only _be_ attributes.
' there are no expression holes here.
For Each attribute In node.Attributes
ClassifyBaseXmlAttribute(TryCast(attribute, BaseXmlAttributeSyntax))
Next
AddXmlClassification(node.SlashGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyBaseXmlAttribute(attribute As BaseXmlAttributeSyntax)
If attribute IsNot Nothing Then
Select Case attribute.Kind
Case SyntaxKind.XmlAttribute
ClassifyAttribute(DirectCast(attribute, XmlAttributeSyntax))
Case SyntaxKind.XmlCrefAttribute
ClassifyCrefAttribute(DirectCast(attribute, XmlCrefAttributeSyntax))
Case SyntaxKind.XmlNameAttribute
ClassifyNameAttribute(DirectCast(attribute, XmlNameAttributeSyntax))
End Select
End If
End Sub
Private Sub ClassifyAttribute(attribute As XmlAttributeSyntax)
ClassifyXmlNode(attribute.Name)
AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlNode(attribute.Value)
End Sub
Private Sub ClassifyCrefAttribute(attribute As XmlCrefAttributeSyntax)
ClassifyXmlNode(attribute.Name)
AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter)
AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
_worker.ClassifyNode(attribute.Reference)
AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
End Sub
Private Sub ClassifyNameAttribute(attribute As XmlNameAttributeSyntax)
ClassifyXmlNode(attribute.Name)
AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter)
AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
_worker.ClassifyNode(attribute.Reference)
AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
End Sub
Private Sub ClassifyXmlText(xmlTextSyntax As XmlTextSyntax)
ClassifyXmlTextTokens(xmlTextSyntax.TextTokens)
End Sub
Private Sub ClassifyString(node As XmlStringSyntax)
AddXmlClassification(node.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
ClassifyXmlTextTokens(node.TextTokens)
AddXmlClassification(node.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
End Sub
Private Sub ClassifyComment(node As XmlCommentSyntax)
AddXmlClassification(node.LessThanExclamationMinusMinusToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlTextTokens(node.TextTokens)
AddXmlClassification(node.MinusMinusGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyCData(node As XmlCDataSectionSyntax)
AddXmlClassification(node.BeginCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlTextTokens(node.TextTokens)
AddXmlClassification(node.EndCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyProcessingInstruction(node As XmlProcessingInstructionSyntax)
AddXmlClassification(node.LessThanQuestionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction)
AddXmlClassification(node.Name, ClassificationTypeNames.XmlDocCommentProcessingInstruction)
ClassifyXmlTextTokens(node.TextTokens)
AddXmlClassification(node.QuestionGreaterThanToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction)
End Sub
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification
Partial Friend Class Worker
Private Class DocumentationCommentClassifier
Private ReadOnly _worker As Worker
Public Sub New(worker As Worker)
_worker = worker
End Sub
Friend Sub Classify(documentationComment As DocumentationCommentTriviaSyntax)
If Not _worker._textSpan.OverlapsWith(documentationComment.Span) Then
Return
End If
For Each xmlNode In documentationComment.Content
Dim childFullSpan = xmlNode.FullSpan
If childFullSpan.Start > _worker._textSpan.End Then
Return
ElseIf childFullSpan.End < _worker._textSpan.Start Then
Continue For
End If
ClassifyXmlNode(xmlNode)
Next
End Sub
Private Sub ClassifyXmlNode(node As XmlNodeSyntax)
If node Is Nothing Then
Return
End If
Select Case node.Kind
Case SyntaxKind.XmlText
ClassifyXmlText(DirectCast(node, XmlTextSyntax))
Case SyntaxKind.XmlElement
ClassifyElement(DirectCast(node, XmlElementSyntax))
Case SyntaxKind.XmlEmptyElement
ClassifyEmptyElement(DirectCast(node, XmlEmptyElementSyntax))
Case SyntaxKind.XmlName
ClassifyXmlName(DirectCast(node, XmlNameSyntax))
Case SyntaxKind.XmlString
ClassifyString(DirectCast(node, XmlStringSyntax))
Case SyntaxKind.XmlComment
ClassifyComment(DirectCast(node, XmlCommentSyntax))
Case SyntaxKind.XmlCDataSection
ClassifyCData(DirectCast(node, XmlCDataSectionSyntax))
Case SyntaxKind.XmlProcessingInstruction
ClassifyProcessingInstruction(DirectCast(node, XmlProcessingInstructionSyntax))
End Select
End Sub
Private Sub ClassifyXmlTrivia(trivialList As SyntaxTriviaList, Optional whitespaceClassificationType As String = Nothing)
For Each t In trivialList
Select Case t.Kind()
Case SyntaxKind.DocumentationCommentExteriorTrivia
ClassifyExteriorTrivia(t)
Case SyntaxKind.WhitespaceTrivia
If whitespaceClassificationType IsNot Nothing Then
_worker.AddClassification(t, whitespaceClassificationType)
End If
End Select
Next
End Sub
Private Sub ClassifyExteriorTrivia(trivia As SyntaxTrivia)
' Note: The exterior trivia can contain whitespace (usually leading) and we want to avoid classifying it.
' PERFORMANCE:
' While the call to SyntaxTrivia.ToString() looks Like an allocation, it isn't.
' The SyntaxTrivia green node holds the string text of the trivia in a field And ToString()
' just returns a reference to that.
Dim text = trivia.ToString()
Dim spanStart As Integer? = Nothing
For index = 0 To text.Length - 1
Dim ch = text(index)
If spanStart IsNot Nothing AndAlso Char.IsWhiteSpace(ch) Then
Dim span = TextSpan.FromBounds(spanStart.Value, spanStart.Value + index)
_worker.AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter)
spanStart = Nothing
ElseIf spanStart Is Nothing AndAlso Not Char.IsWhiteSpace(ch) Then
spanStart = trivia.Span.Start + index
End If
Next
' Add a final classification if we hadn't encountered anymore whitespace at the end
If spanStart IsNot Nothing Then
Dim span = TextSpan.FromBounds(spanStart.Value, trivia.Span.End)
_worker.AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter)
End If
End Sub
Private Sub AddXmlClassification(token As SyntaxToken, classificationType As String)
If token.HasLeadingTrivia Then
ClassifyXmlTrivia(token.LeadingTrivia, classificationType)
End If
_worker.AddClassification(token, classificationType)
If token.HasTrailingTrivia Then
ClassifyXmlTrivia(token.TrailingTrivia, classificationType)
End If
End Sub
Private Sub ClassifyXmlTextTokens(textTokens As SyntaxTokenList)
For Each token In textTokens
If token.HasLeadingTrivia Then
ClassifyXmlTrivia(token.LeadingTrivia, whitespaceClassificationType:=ClassificationTypeNames.XmlDocCommentText)
End If
ClassifyXmlTextToken(token)
If token.HasTrailingTrivia Then
ClassifyXmlTrivia(token.TrailingTrivia, whitespaceClassificationType:=ClassificationTypeNames.XmlDocCommentText)
End If
Next token
End Sub
Private Sub ClassifyXmlTextToken(token As SyntaxToken)
If token.Kind = SyntaxKind.XmlEntityLiteralToken Then
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentEntityReference)
ElseIf token.Kind() <> SyntaxKind.DocumentationCommentLineBreakToken Then
Select Case token.Parent.Kind
Case SyntaxKind.XmlText
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentText)
Case SyntaxKind.XmlString
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentAttributeValue)
Case SyntaxKind.XmlComment
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentComment)
Case SyntaxKind.XmlCDataSection
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentCDataSection)
Case SyntaxKind.XmlProcessingInstruction
_worker.AddClassification(token, ClassificationTypeNames.XmlDocCommentProcessingInstruction)
End Select
End If
End Sub
Private Sub ClassifyXmlName(node As XmlNameSyntax)
Dim classificationType As String
If TypeOf node.Parent Is BaseXmlAttributeSyntax Then
classificationType = ClassificationTypeNames.XmlDocCommentAttributeName
ElseIf TypeOf node.Parent Is XmlProcessingInstructionSyntax Then
classificationType = ClassificationTypeNames.XmlDocCommentProcessingInstruction
Else
classificationType = ClassificationTypeNames.XmlDocCommentName
End If
Dim prefix = node.Prefix
If prefix IsNot Nothing Then
AddXmlClassification(prefix.Name, classificationType)
AddXmlClassification(prefix.ColonToken, classificationType)
End If
AddXmlClassification(node.LocalName, classificationType)
End Sub
Private Sub ClassifyElement(xmlElementSyntax As XmlElementSyntax)
ClassifyElementStart(xmlElementSyntax.StartTag)
For Each xmlNode In xmlElementSyntax.Content
ClassifyXmlNode(xmlNode)
Next
ClassifyElementEnd(xmlElementSyntax.EndTag)
End Sub
Private Sub ClassifyElementStart(node As XmlElementStartTagSyntax)
AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlNode(node.Name)
' Note: In xml doc comments, attributes can only _be_ attributes.
' there are no expression holes here.
For Each attribute In node.Attributes
ClassifyBaseXmlAttribute(TryCast(attribute, BaseXmlAttributeSyntax))
Next
AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyElementEnd(node As XmlElementEndTagSyntax)
AddXmlClassification(node.LessThanSlashToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlNode(node.Name)
AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyEmptyElement(node As XmlEmptyElementSyntax)
AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlNode(node.Name)
' Note: In xml doc comments, attributes can only _be_ attributes.
' there are no expression holes here.
For Each attribute In node.Attributes
ClassifyBaseXmlAttribute(TryCast(attribute, BaseXmlAttributeSyntax))
Next
AddXmlClassification(node.SlashGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyBaseXmlAttribute(attribute As BaseXmlAttributeSyntax)
If attribute IsNot Nothing Then
Select Case attribute.Kind
Case SyntaxKind.XmlAttribute
ClassifyAttribute(DirectCast(attribute, XmlAttributeSyntax))
Case SyntaxKind.XmlCrefAttribute
ClassifyCrefAttribute(DirectCast(attribute, XmlCrefAttributeSyntax))
Case SyntaxKind.XmlNameAttribute
ClassifyNameAttribute(DirectCast(attribute, XmlNameAttributeSyntax))
End Select
End If
End Sub
Private Sub ClassifyAttribute(attribute As XmlAttributeSyntax)
ClassifyXmlNode(attribute.Name)
AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlNode(attribute.Value)
End Sub
Private Sub ClassifyCrefAttribute(attribute As XmlCrefAttributeSyntax)
ClassifyXmlNode(attribute.Name)
AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter)
AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
_worker.ClassifyNode(attribute.Reference)
AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
End Sub
Private Sub ClassifyNameAttribute(attribute As XmlNameAttributeSyntax)
ClassifyXmlNode(attribute.Name)
AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter)
AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
_worker.ClassifyNode(attribute.Reference)
AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
End Sub
Private Sub ClassifyXmlText(xmlTextSyntax As XmlTextSyntax)
ClassifyXmlTextTokens(xmlTextSyntax.TextTokens)
End Sub
Private Sub ClassifyString(node As XmlStringSyntax)
AddXmlClassification(node.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
ClassifyXmlTextTokens(node.TextTokens)
AddXmlClassification(node.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes)
End Sub
Private Sub ClassifyComment(node As XmlCommentSyntax)
AddXmlClassification(node.LessThanExclamationMinusMinusToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlTextTokens(node.TextTokens)
AddXmlClassification(node.MinusMinusGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyCData(node As XmlCDataSectionSyntax)
AddXmlClassification(node.BeginCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter)
ClassifyXmlTextTokens(node.TextTokens)
AddXmlClassification(node.EndCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter)
End Sub
Private Sub ClassifyProcessingInstruction(node As XmlProcessingInstructionSyntax)
AddXmlClassification(node.LessThanQuestionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction)
AddXmlClassification(node.Name, ClassificationTypeNames.XmlDocCommentProcessingInstruction)
ClassifyXmlTextTokens(node.TextTokens)
AddXmlClassification(node.QuestionGreaterThanToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction)
End Sub
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Interactive/HostTest/StressTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
extern alias InteractiveHost;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
public sealed class StressTests
{
[Fact]
public async Task TestKill()
{
for (int sleep = 0; sleep < 20; sleep++)
{
await TestKillAfterAsync(sleep).ConfigureAwait(false);
}
}
private async Task TestKillAfterAsync(int milliseconds)
{
using var host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: 1, joinOutputWritingThreadsOnDisposal: true);
var options = InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop64);
host.InteractiveHostProcessCreated += new Action<Process>(proc =>
{
_ = Task.Run(async () =>
{
await Task.Delay(milliseconds).ConfigureAwait(false);
try
{
proc.Kill();
}
catch
{
}
});
});
await host.ResetAsync(options).ConfigureAwait(false);
for (int j = 0; j < 10; j++)
{
await host.ExecuteAsync("1+1").ConfigureAwait(false);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
extern alias InteractiveHost;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
using InteractiveHost::Microsoft.CodeAnalysis.Interactive;
public sealed class StressTests
{
[Fact]
public async Task TestKill()
{
for (int sleep = 0; sleep < 20; sleep++)
{
await TestKillAfterAsync(sleep).ConfigureAwait(false);
}
}
private async Task TestKillAfterAsync(int milliseconds)
{
using var host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: 1, joinOutputWritingThreadsOnDisposal: true);
var options = InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop64);
host.InteractiveHostProcessCreated += new Action<Process>(proc =>
{
_ = Task.Run(async () =>
{
await Task.Delay(milliseconds).ConfigureAwait(false);
try
{
proc.Kill();
}
catch
{
}
});
});
await host.ResetAsync(options).ConfigureAwait(false);
for (int j = 0; j < 10; j++)
{
await host.ExecuteAsync("1+1").ConfigureAwait(false);
}
}
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/Core/Portable/SourceGeneration/IncrementalGeneratorSyntaxWalker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis
{
internal sealed class IncrementalGeneratorSyntaxWalker : SyntaxWalker
{
private readonly Func<SyntaxNode, CancellationToken, bool> _filter;
private readonly CancellationToken _token;
private ArrayBuilder<SyntaxNode>? _results;
internal IncrementalGeneratorSyntaxWalker(Func<SyntaxNode, CancellationToken, bool> filter, CancellationToken token)
{
_filter = filter;
_token = token;
}
public static ImmutableArray<SyntaxNode> GetFilteredNodes(SyntaxNode root, Func<SyntaxNode, CancellationToken, bool> func, CancellationToken token)
{
var walker = new IncrementalGeneratorSyntaxWalker(func, token);
walker.Visit(root);
return walker._results.ToImmutableOrEmptyAndFree();
}
public override void Visit(SyntaxNode node)
{
_token.ThrowIfCancellationRequested();
if (_filter(node, _token))
{
(_results ??= ArrayBuilder<SyntaxNode>.GetInstance()).Add(node);
}
base.Visit(node);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis
{
internal sealed class IncrementalGeneratorSyntaxWalker : SyntaxWalker
{
private readonly Func<SyntaxNode, CancellationToken, bool> _filter;
private readonly CancellationToken _token;
private ArrayBuilder<SyntaxNode>? _results;
internal IncrementalGeneratorSyntaxWalker(Func<SyntaxNode, CancellationToken, bool> filter, CancellationToken token)
{
_filter = filter;
_token = token;
}
public static ImmutableArray<SyntaxNode> GetFilteredNodes(SyntaxNode root, Func<SyntaxNode, CancellationToken, bool> func, CancellationToken token)
{
var walker = new IncrementalGeneratorSyntaxWalker(func, token);
walker.Visit(root);
return walker._results.ToImmutableOrEmptyAndFree();
}
public override void Visit(SyntaxNode node)
{
_token.ThrowIfCancellationRequested();
if (_filter(node, _token))
{
(_results ??= ArrayBuilder<SyntaxNode>.GetInstance()).Add(node);
}
base.Visit(node);
}
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicErrorListCommon.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
public class BasicErrorListCommon : AbstractEditorTest
{
public BasicErrorListCommon(VisualStudioInstanceFactory instanceFactory, string templateName)
: base(instanceFactory, nameof(BasicErrorListCommon), templateName)
{
}
protected override string LanguageName => LanguageNames.VisualBasic;
public virtual void ErrorList()
{
VisualStudio.Editor.SetText(@"
Module Module1
Function Good() As P
Return Nothing
End Function
Sub Main()
Goo()
End Sub
End Module
");
VisualStudio.ErrorList.ShowErrorList();
var expectedContents = new[] {
new ErrorListItem(
severity: "Error",
description: "Type 'P' is not defined.",
project: "TestProj",
fileName: "Class1.vb",
line: 4,
column: 24),
new ErrorListItem(
severity: "Error",
description: "'Goo' is not declared. It may be inaccessible due to its protection level.",
project: "TestProj",
fileName: "Class1.vb",
line: 9,
column: 9)
};
var actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
VisualStudio.ErrorList.NavigateToErrorListItem(0);
VisualStudio.Editor.Verify.CaretPosition(43);
VisualStudio.SolutionExplorer.BuildSolution();
VisualStudio.ErrorList.ShowErrorList();
actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
}
public virtual void ErrorsDuringMethodBodyEditing()
{
VisualStudio.Editor.SetText(@"
Namespace N
Class C
Private F As Integer
Sub S()
' Comment
End Sub
End Class
End Namespace
");
VisualStudio.Editor.PlaceCaret(" Comment", charsOffset: -2);
VisualStudio.SendKeys.Send("F = 0");
VisualStudio.ErrorList.ShowErrorList();
var expectedContents = new ErrorListItem[] { };
var actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
VisualStudio.Editor.Activate();
VisualStudio.Editor.PlaceCaret("F = 0 ' Comment", charsOffset: -1);
VisualStudio.Editor.SendKeys("F");
VisualStudio.ErrorList.ShowErrorList();
expectedContents = new ErrorListItem[] {
new ErrorListItem(
severity: "Error",
description: "'FF' is not declared. It may be inaccessible due to its protection level.",
project: "TestProj",
fileName: "Class1.vb",
line: 6,
column: 13)
};
actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
VisualStudio.Editor.Activate();
VisualStudio.Editor.PlaceCaret("FF = 0 ' Comment", charsOffset: -1);
VisualStudio.Editor.SendKeys(VirtualKey.Delete);
VisualStudio.ErrorList.ShowErrorList();
expectedContents = new ErrorListItem[] { };
actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
public class BasicErrorListCommon : AbstractEditorTest
{
public BasicErrorListCommon(VisualStudioInstanceFactory instanceFactory, string templateName)
: base(instanceFactory, nameof(BasicErrorListCommon), templateName)
{
}
protected override string LanguageName => LanguageNames.VisualBasic;
public virtual void ErrorList()
{
VisualStudio.Editor.SetText(@"
Module Module1
Function Good() As P
Return Nothing
End Function
Sub Main()
Goo()
End Sub
End Module
");
VisualStudio.ErrorList.ShowErrorList();
var expectedContents = new[] {
new ErrorListItem(
severity: "Error",
description: "Type 'P' is not defined.",
project: "TestProj",
fileName: "Class1.vb",
line: 4,
column: 24),
new ErrorListItem(
severity: "Error",
description: "'Goo' is not declared. It may be inaccessible due to its protection level.",
project: "TestProj",
fileName: "Class1.vb",
line: 9,
column: 9)
};
var actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
VisualStudio.ErrorList.NavigateToErrorListItem(0);
VisualStudio.Editor.Verify.CaretPosition(43);
VisualStudio.SolutionExplorer.BuildSolution();
VisualStudio.ErrorList.ShowErrorList();
actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
}
public virtual void ErrorsDuringMethodBodyEditing()
{
VisualStudio.Editor.SetText(@"
Namespace N
Class C
Private F As Integer
Sub S()
' Comment
End Sub
End Class
End Namespace
");
VisualStudio.Editor.PlaceCaret(" Comment", charsOffset: -2);
VisualStudio.SendKeys.Send("F = 0");
VisualStudio.ErrorList.ShowErrorList();
var expectedContents = new ErrorListItem[] { };
var actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
VisualStudio.Editor.Activate();
VisualStudio.Editor.PlaceCaret("F = 0 ' Comment", charsOffset: -1);
VisualStudio.Editor.SendKeys("F");
VisualStudio.ErrorList.ShowErrorList();
expectedContents = new ErrorListItem[] {
new ErrorListItem(
severity: "Error",
description: "'FF' is not declared. It may be inaccessible due to its protection level.",
project: "TestProj",
fileName: "Class1.vb",
line: 6,
column: 13)
};
actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
VisualStudio.Editor.Activate();
VisualStudio.Editor.PlaceCaret("FF = 0 ' Comment", charsOffset: -1);
VisualStudio.Editor.SendKeys(VirtualKey.Delete);
VisualStudio.ErrorList.ShowErrorList();
expectedContents = new ErrorListItem[] { };
actualContents = VisualStudio.ErrorList.GetErrorListContents();
AssertEx.EqualOrDiff(
string.Join<ErrorListItem>(Environment.NewLine, expectedContents),
string.Join<ErrorListItem>(Environment.NewLine, actualContents));
}
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Workspaces/Core/Portable/Formatting/Rules/IFormattingRule.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Formatting.Rules
{
[Obsolete("This interface is no longer used")]
internal interface IFormattingRule
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Formatting.Rules
{
[Obsolete("This interface is no longer used")]
internal interface IFormattingRule
{
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Workspaces/Remote/Core/ISolutionSynchronizationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Remote
{
internal interface ISolutionAssetStorageProvider : IWorkspaceService
{
SolutionAssetStorage AssetStorage { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Remote
{
internal interface ISolutionAssetStorageProvider : IWorkspaceService
{
SolutionAssetStorage AssetStorage { get; }
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/CSharp/Test/Semantic/Semantics/InteractiveSemanticModelTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class SemanticModelTests : CSharpTestBase
{
[Fact]
public void NamespaceBindingInInteractiveCode()
{
var compilation = CreateCompilation(@"
using Z = Goo.Bar.Script.C;
class C { }
namespace Goo.Bar
{
class B : Z { }
}
",
parseOptions: TestOptions.Script,
options: TestOptions.ReleaseExe.WithScriptClassName("Goo.Bar.Script")
);
var tree = compilation.SyntaxTrees[0];
var root = tree.GetCompilationUnitRoot();
var classB = (root.Members[1] as NamespaceDeclarationSyntax).Members[0] as TypeDeclarationSyntax;
var model = compilation.GetSemanticModel(tree);
var symbol = model.GetDeclaredSymbol(classB);
var baseType = symbol?.BaseType;
Assert.NotNull(baseType);
Assert.Equal(TypeKind.Error, baseType.TypeKind);
Assert.Equal(LookupResultKind.Inaccessible, baseType.GetSymbol<ErrorTypeSymbol>().ResultKind); // Script class members are private.
}
[Fact]
public void CompilationChain_OverloadsWithParams()
{
CompileAndVerifyBindInfo(@"
public static string[] str = null;
public static void Goo(string[] r, string i) { str = r;}
public static void Goo(params string[] r) { str = r;}
/*<bind>*/ Goo(""1"", ""2"") /*</bind>*/;",
"Goo(params string[])");
}
[Fact]
public void CompilationChain_NestedTypesClass()
{
CompileAndVerifyBindInfo(@"
class InnerClass
{
public string innerStr = null;
public string Goo() { return innerStr;}
}
InnerClass iC = new InnerClass();
/*<bind>*/ iC.Goo(); /*</bind>*/",
"InnerClass.Goo()");
}
[Fact]
public void MethodCallBinding()
{
var testSrc = @"
void Goo() {};
/*<bind>*/Goo()/*</bind>*/;
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.NotNull(bindInfo.Type);
Assert.Equal("System.Void", bindInfo.Type.ToTestDisplayString());
}
[Fact]
public void BindNullLiteral()
{
var testSrc = @"string s = /*<bind>*/null/*</bind>*/;";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.Null(bindInfo.Type);
}
[Fact]
public void BindBooleanField()
{
var testSrc = @"
bool result = true ;
/*<bind>*/ result /*</bind>*/= false;
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.NotNull(bindInfo.Type);
Assert.Equal("System.Boolean", bindInfo.Type.ToTestDisplayString());
}
[Fact]
public void BindLocals()
{
var testSrc = @"
const int constantField = 1;
int field = constantField;
{
int local1 = field;
int local2 = /*<bind>*/local1/*</bind>*/;
}
{
int local2 = constantField;
}";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType);
var symbol = bindInfo.Symbol;
Assert.Equal("System.Int32 local1", symbol.ToTestDisplayString());
Assert.IsAssignableFrom<SourceLocalSymbol>(symbol.GetSymbol());
}
[WorkItem(540513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540513")]
[Fact]
public void BindVariableInGlobalStatement()
{
var testSrc = @"
int i = 2;
++/*<bind>*/i/*</bind>*/;";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType);
var symbol = bindInfo.Symbol;
Assert.Equal("System.Int32 Script.i", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, symbol.Kind);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void BindVarKeyword()
{
var testSrc = @"
/*<bind>*/var/*</bind>*/ rand = new System.Random();";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("System.Random", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Random", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Random", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void BindVarKeyword_MultipleDeclarators()
{
string testSrc = @"
/*<bind>*/var/*</bind>*/ i = new int(), j = new char();
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void BindVarNamedType()
{
string testSrc = @"
public class var { }
/*<bind>*/var/*</bind>*/ x = new var();
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("Script.var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Script.var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Script.var", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void BindVarNamedType_Ambiguous()
{
string testSrc = @"
using System;
public class var { }
public struct var { }
/*<bind>*/var/*</bind>*/ x = new var();
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("Script.var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Script.var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString()).ToArray();
Assert.Equal("Script.var", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("Script.var", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543864")]
[Fact]
public void BindQueryVariable()
{
string testSrc = @"
using System.Linq;
var x = from c in ""goo"" select /*<bind>*/c/*</bind>*/";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("c", semanticInfo.Symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, semanticInfo.Symbol.Kind);
Assert.Equal(SpecialType.System_Char, semanticInfo.Type.SpecialType);
}
#region helpers
private List<ExpressionSyntax> GetExprSyntaxList(SyntaxTree syntaxTree)
{
return GetExprSyntaxList(syntaxTree.GetCompilationUnitRoot(), null);
}
private List<ExpressionSyntax> GetExprSyntaxList(SyntaxNode node, List<ExpressionSyntax> exprSynList)
{
if (exprSynList == null)
exprSynList = new List<ExpressionSyntax>();
if (node is ExpressionSyntax)
{
exprSynList.Add(node as ExpressionSyntax);
}
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
exprSynList = GetExprSyntaxList(child.AsNode(), exprSynList);
}
return exprSynList;
}
private ExpressionSyntax GetExprSyntaxForBinding(List<ExpressionSyntax> exprSynList)
{
foreach (var exprSyntax in exprSynList)
{
string exprFullText = exprSyntax.ToFullString();
exprFullText = exprFullText.Trim();
if (exprFullText.StartsWith("/*<bind>*/", StringComparison.Ordinal))
{
if (exprFullText.Contains("/*</bind>*/"))
{
if (exprFullText.EndsWith("/*</bind>*/", StringComparison.Ordinal))
{
return exprSyntax;
}
else
{
continue;
}
}
else
{
return exprSyntax;
}
}
if (exprFullText.EndsWith("/*</bind>*/", StringComparison.Ordinal))
{
if (exprFullText.Contains("/*<bind>*/"))
{
if (exprFullText.StartsWith("/*<bind>*/", StringComparison.Ordinal))
{
return exprSyntax;
}
else
{
continue;
}
}
else
{
return exprSyntax;
}
}
}
return null;
}
private void CompileAndVerifyBindInfo(string testSrc, string expected)
{
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.NotNull(bindInfo.Type);
var method = bindInfo.Symbol.ToDisplayString();
Assert.Equal(expected, method);
}
private CompilationUtils.SemanticInfoSummary GetBindInfoForTest(string testSrc)
{
var compilation = CreateCompilation(testSrc, parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
return model.GetSemanticInfoSummary(exprSyntaxToBind);
}
#endregion helpers
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class SemanticModelTests : CSharpTestBase
{
[Fact]
public void NamespaceBindingInInteractiveCode()
{
var compilation = CreateCompilation(@"
using Z = Goo.Bar.Script.C;
class C { }
namespace Goo.Bar
{
class B : Z { }
}
",
parseOptions: TestOptions.Script,
options: TestOptions.ReleaseExe.WithScriptClassName("Goo.Bar.Script")
);
var tree = compilation.SyntaxTrees[0];
var root = tree.GetCompilationUnitRoot();
var classB = (root.Members[1] as NamespaceDeclarationSyntax).Members[0] as TypeDeclarationSyntax;
var model = compilation.GetSemanticModel(tree);
var symbol = model.GetDeclaredSymbol(classB);
var baseType = symbol?.BaseType;
Assert.NotNull(baseType);
Assert.Equal(TypeKind.Error, baseType.TypeKind);
Assert.Equal(LookupResultKind.Inaccessible, baseType.GetSymbol<ErrorTypeSymbol>().ResultKind); // Script class members are private.
}
[Fact]
public void CompilationChain_OverloadsWithParams()
{
CompileAndVerifyBindInfo(@"
public static string[] str = null;
public static void Goo(string[] r, string i) { str = r;}
public static void Goo(params string[] r) { str = r;}
/*<bind>*/ Goo(""1"", ""2"") /*</bind>*/;",
"Goo(params string[])");
}
[Fact]
public void CompilationChain_NestedTypesClass()
{
CompileAndVerifyBindInfo(@"
class InnerClass
{
public string innerStr = null;
public string Goo() { return innerStr;}
}
InnerClass iC = new InnerClass();
/*<bind>*/ iC.Goo(); /*</bind>*/",
"InnerClass.Goo()");
}
[Fact]
public void MethodCallBinding()
{
var testSrc = @"
void Goo() {};
/*<bind>*/Goo()/*</bind>*/;
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.NotNull(bindInfo.Type);
Assert.Equal("System.Void", bindInfo.Type.ToTestDisplayString());
}
[Fact]
public void BindNullLiteral()
{
var testSrc = @"string s = /*<bind>*/null/*</bind>*/;";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.Null(bindInfo.Type);
}
[Fact]
public void BindBooleanField()
{
var testSrc = @"
bool result = true ;
/*<bind>*/ result /*</bind>*/= false;
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.NotNull(bindInfo.Type);
Assert.Equal("System.Boolean", bindInfo.Type.ToTestDisplayString());
}
[Fact]
public void BindLocals()
{
var testSrc = @"
const int constantField = 1;
int field = constantField;
{
int local1 = field;
int local2 = /*<bind>*/local1/*</bind>*/;
}
{
int local2 = constantField;
}";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType);
var symbol = bindInfo.Symbol;
Assert.Equal("System.Int32 local1", symbol.ToTestDisplayString());
Assert.IsAssignableFrom<SourceLocalSymbol>(symbol.GetSymbol());
}
[WorkItem(540513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540513")]
[Fact]
public void BindVariableInGlobalStatement()
{
var testSrc = @"
int i = 2;
++/*<bind>*/i/*</bind>*/;";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.Equal(SpecialType.System_Int32, bindInfo.Type.SpecialType);
var symbol = bindInfo.Symbol;
Assert.Equal("System.Int32 Script.i", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, symbol.Kind);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void BindVarKeyword()
{
var testSrc = @"
/*<bind>*/var/*</bind>*/ rand = new System.Random();";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("System.Random", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Random", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Random", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void BindVarKeyword_MultipleDeclarators()
{
string testSrc = @"
/*<bind>*/var/*</bind>*/ i = new int(), j = new char();
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void BindVarNamedType()
{
string testSrc = @"
public class var { }
/*<bind>*/var/*</bind>*/ x = new var();
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("Script.var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Script.var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Script.var", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void BindVarNamedType_Ambiguous()
{
string testSrc = @"
using System;
public class var { }
public struct var { }
/*<bind>*/var/*</bind>*/ x = new var();
";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("Script.var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Script.var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString()).ToArray();
Assert.Equal("Script.var", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("Script.var", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543864")]
[Fact]
public void BindQueryVariable()
{
string testSrc = @"
using System.Linq;
var x = from c in ""goo"" select /*<bind>*/c/*</bind>*/";
// Get the bind info for the text identified within the commented <bind> </bind> tags
var semanticInfo = GetBindInfoForTest(testSrc);
Assert.Equal("c", semanticInfo.Symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, semanticInfo.Symbol.Kind);
Assert.Equal(SpecialType.System_Char, semanticInfo.Type.SpecialType);
}
#region helpers
private List<ExpressionSyntax> GetExprSyntaxList(SyntaxTree syntaxTree)
{
return GetExprSyntaxList(syntaxTree.GetCompilationUnitRoot(), null);
}
private List<ExpressionSyntax> GetExprSyntaxList(SyntaxNode node, List<ExpressionSyntax> exprSynList)
{
if (exprSynList == null)
exprSynList = new List<ExpressionSyntax>();
if (node is ExpressionSyntax)
{
exprSynList.Add(node as ExpressionSyntax);
}
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
exprSynList = GetExprSyntaxList(child.AsNode(), exprSynList);
}
return exprSynList;
}
private ExpressionSyntax GetExprSyntaxForBinding(List<ExpressionSyntax> exprSynList)
{
foreach (var exprSyntax in exprSynList)
{
string exprFullText = exprSyntax.ToFullString();
exprFullText = exprFullText.Trim();
if (exprFullText.StartsWith("/*<bind>*/", StringComparison.Ordinal))
{
if (exprFullText.Contains("/*</bind>*/"))
{
if (exprFullText.EndsWith("/*</bind>*/", StringComparison.Ordinal))
{
return exprSyntax;
}
else
{
continue;
}
}
else
{
return exprSyntax;
}
}
if (exprFullText.EndsWith("/*</bind>*/", StringComparison.Ordinal))
{
if (exprFullText.Contains("/*<bind>*/"))
{
if (exprFullText.StartsWith("/*<bind>*/", StringComparison.Ordinal))
{
return exprSyntax;
}
else
{
continue;
}
}
else
{
return exprSyntax;
}
}
}
return null;
}
private void CompileAndVerifyBindInfo(string testSrc, string expected)
{
// Get the bind info for the text identified within the commented <bind> </bind> tags
var bindInfo = GetBindInfoForTest(testSrc);
Assert.NotNull(bindInfo.Type);
var method = bindInfo.Symbol.ToDisplayString();
Assert.Equal(expected, method);
}
private CompilationUtils.SemanticInfoSummary GetBindInfoForTest(string testSrc)
{
var compilation = CreateCompilation(testSrc, parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var exprSyntaxToBind = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
return model.GetSemanticInfoSummary(exprSyntaxToBind);
}
#endregion helpers
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.AutoClosingViewProperty.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static partial class ITextViewExtensions
{
private class AutoClosingViewProperty<TProperty, TTextView> where TTextView : ITextView
{
private readonly TTextView _textView;
private readonly Dictionary<object, TProperty> _map = new();
public static bool GetOrCreateValue(
TTextView textView,
object key,
Func<TTextView, TProperty> valueCreator,
out TProperty value)
{
Contract.ThrowIfTrue(textView.IsClosed);
var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView));
if (!properties.TryGetValue(key, out var priorValue))
{
// Need to create it.
value = valueCreator(textView);
properties.Add(key, value);
return true;
}
// Already there.
value = priorValue;
return false;
}
public static bool TryGetValue(
TTextView textView,
object key,
[MaybeNullWhen(false)] out TProperty value)
{
Contract.ThrowIfTrue(textView.IsClosed);
var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView));
return properties.TryGetValue(key, out value);
}
public static void AddValue(
TTextView textView,
object key,
TProperty value)
{
Contract.ThrowIfTrue(textView.IsClosed);
var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView));
properties.Add(key, value);
}
public static void RemoveValue(TTextView textView, object key)
{
if (textView.Properties.TryGetProperty(typeof(AutoClosingViewProperty<TProperty, TTextView>), out AutoClosingViewProperty<TProperty, TTextView> properties))
{
properties.Remove(key);
}
}
private AutoClosingViewProperty(TTextView textView)
{
_textView = textView;
_textView.Closed += OnTextViewClosed;
}
private void OnTextViewClosed(object? sender, EventArgs e)
{
_textView.Closed -= OnTextViewClosed;
_textView.Properties.RemoveProperty(typeof(AutoClosingViewProperty<TProperty, TTextView>));
}
public bool TryGetValue(object key, [MaybeNullWhen(false)] out TProperty value)
=> _map.TryGetValue(key, out value);
public void Add(object key, TProperty value)
=> _map[key] = value;
public void Remove(object key)
=> _map.Remove(key);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static partial class ITextViewExtensions
{
private class AutoClosingViewProperty<TProperty, TTextView> where TTextView : ITextView
{
private readonly TTextView _textView;
private readonly Dictionary<object, TProperty> _map = new();
public static bool GetOrCreateValue(
TTextView textView,
object key,
Func<TTextView, TProperty> valueCreator,
out TProperty value)
{
Contract.ThrowIfTrue(textView.IsClosed);
var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView));
if (!properties.TryGetValue(key, out var priorValue))
{
// Need to create it.
value = valueCreator(textView);
properties.Add(key, value);
return true;
}
// Already there.
value = priorValue;
return false;
}
public static bool TryGetValue(
TTextView textView,
object key,
[MaybeNullWhen(false)] out TProperty value)
{
Contract.ThrowIfTrue(textView.IsClosed);
var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView));
return properties.TryGetValue(key, out value);
}
public static void AddValue(
TTextView textView,
object key,
TProperty value)
{
Contract.ThrowIfTrue(textView.IsClosed);
var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView));
properties.Add(key, value);
}
public static void RemoveValue(TTextView textView, object key)
{
if (textView.Properties.TryGetProperty(typeof(AutoClosingViewProperty<TProperty, TTextView>), out AutoClosingViewProperty<TProperty, TTextView> properties))
{
properties.Remove(key);
}
}
private AutoClosingViewProperty(TTextView textView)
{
_textView = textView;
_textView.Closed += OnTextViewClosed;
}
private void OnTextViewClosed(object? sender, EventArgs e)
{
_textView.Closed -= OnTextViewClosed;
_textView.Properties.RemoveProperty(typeof(AutoClosingViewProperty<TProperty, TTextView>));
}
public bool TryGetValue(object key, [MaybeNullWhen(false)] out TProperty value)
=> _map.TryGetValue(key, out value);
public void Add(object key, TProperty value)
=> _map[key] = value;
public void Remove(object key)
=> _map.Remove(key);
}
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/CSharp/Portable/Syntax/ForStatementSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 ForStatementSyntax
{
public ForStatementSyntax Update(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement)
=> Update(AttributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static ForStatementSyntax ForStatement(VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, ExpressionSyntax? condition, SeparatedSyntaxList<ExpressionSyntax> incrementors, StatementSyntax statement)
=> ForStatement(attributeLists: default, declaration, initializers, condition, incrementors, statement);
public static ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement)
=> ForStatement(attributeLists: default, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 ForStatementSyntax
{
public ForStatementSyntax Update(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement)
=> Update(AttributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static ForStatementSyntax ForStatement(VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, ExpressionSyntax? condition, SeparatedSyntaxList<ExpressionSyntax> incrementors, StatementSyntax statement)
=> ForStatement(attributeLists: default, declaration, initializers, condition, incrementors, statement);
public static ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement)
=> ForStatement(attributeLists: default, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement);
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/Core/Portable/Collections/Boxes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
internal static class Boxes
{
public static readonly object BoxedTrue = true;
public static readonly object BoxedFalse = false;
public static readonly object BoxedByteZero = (byte)0;
public static readonly object BoxedSByteZero = (sbyte)0;
public static readonly object BoxedInt16Zero = (short)0;
public static readonly object BoxedUInt16Zero = (ushort)0;
public static readonly object BoxedInt32Zero = 0;
public static readonly object BoxedInt32One = 1;
public static readonly object BoxedUInt32Zero = 0U;
public static readonly object BoxedInt64Zero = 0L;
public static readonly object BoxedUInt64Zero = 0UL;
public static readonly object BoxedSingleZero = 0.0f;
public static readonly object BoxedDoubleZero = 0.0;
public static readonly object BoxedDecimalZero = 0m;
private static readonly object?[] s_boxedAsciiChars = new object?[128];
public static object Box(bool b)
{
return b ? BoxedTrue : BoxedFalse;
}
public static object Box(byte b)
{
return b == 0 ? BoxedByteZero : b;
}
public static object Box(sbyte sb)
{
return sb == 0 ? BoxedSByteZero : sb;
}
public static object Box(short s)
{
return s == 0 ? BoxedInt16Zero : s;
}
public static object Box(ushort us)
{
return us == 0 ? BoxedUInt16Zero : us;
}
public static object Box(int i)
{
switch (i)
{
case 0: return BoxedInt32Zero;
case 1: return BoxedInt32One;
default: return i;
}
}
public static object Box(uint u)
{
return u == 0 ? BoxedUInt32Zero : u;
}
public static object Box(long l)
{
return l == 0 ? BoxedInt64Zero : l;
}
public static object Box(ulong ul)
{
return ul == 0 ? BoxedUInt64Zero : ul;
}
public static unsafe object Box(float f)
{
// There are many representations of zero in floating point.
// Use the boxed value only if the bit pattern is all zeros.
return *(int*)(&f) == 0 ? BoxedSingleZero : f;
}
public static object Box(double d)
{
// There are many representations of zero in floating point.
// Use the boxed value only if the bit pattern is all zeros.
return BitConverter.DoubleToInt64Bits(d) == 0 ? BoxedDoubleZero : d;
}
public static object Box(char c)
{
return c < 128
? s_boxedAsciiChars[c] ?? (s_boxedAsciiChars[c] = c)
: c;
}
public static unsafe object Box(decimal d)
{
// There are many representation of zero in System.Decimal
// Use the boxed value only if the bit pattern is all zeros.
ulong* ptr = (ulong*)&d;
return ptr[0] == 0 && ptr[1] == 0 ? BoxedDecimalZero : d;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
internal static class Boxes
{
public static readonly object BoxedTrue = true;
public static readonly object BoxedFalse = false;
public static readonly object BoxedByteZero = (byte)0;
public static readonly object BoxedSByteZero = (sbyte)0;
public static readonly object BoxedInt16Zero = (short)0;
public static readonly object BoxedUInt16Zero = (ushort)0;
public static readonly object BoxedInt32Zero = 0;
public static readonly object BoxedInt32One = 1;
public static readonly object BoxedUInt32Zero = 0U;
public static readonly object BoxedInt64Zero = 0L;
public static readonly object BoxedUInt64Zero = 0UL;
public static readonly object BoxedSingleZero = 0.0f;
public static readonly object BoxedDoubleZero = 0.0;
public static readonly object BoxedDecimalZero = 0m;
private static readonly object?[] s_boxedAsciiChars = new object?[128];
public static object Box(bool b)
{
return b ? BoxedTrue : BoxedFalse;
}
public static object Box(byte b)
{
return b == 0 ? BoxedByteZero : b;
}
public static object Box(sbyte sb)
{
return sb == 0 ? BoxedSByteZero : sb;
}
public static object Box(short s)
{
return s == 0 ? BoxedInt16Zero : s;
}
public static object Box(ushort us)
{
return us == 0 ? BoxedUInt16Zero : us;
}
public static object Box(int i)
{
switch (i)
{
case 0: return BoxedInt32Zero;
case 1: return BoxedInt32One;
default: return i;
}
}
public static object Box(uint u)
{
return u == 0 ? BoxedUInt32Zero : u;
}
public static object Box(long l)
{
return l == 0 ? BoxedInt64Zero : l;
}
public static object Box(ulong ul)
{
return ul == 0 ? BoxedUInt64Zero : ul;
}
public static unsafe object Box(float f)
{
// There are many representations of zero in floating point.
// Use the boxed value only if the bit pattern is all zeros.
return *(int*)(&f) == 0 ? BoxedSingleZero : f;
}
public static object Box(double d)
{
// There are many representations of zero in floating point.
// Use the boxed value only if the bit pattern is all zeros.
return BitConverter.DoubleToInt64Bits(d) == 0 ? BoxedDoubleZero : d;
}
public static object Box(char c)
{
return c < 128
? s_boxedAsciiChars[c] ?? (s_boxedAsciiChars[c] = c)
: c;
}
public static unsafe object Box(decimal d)
{
// There are many representation of zero in System.Decimal
// Use the boxed value only if the bit pattern is all zeros.
ulong* ptr = (ulong*)&d;
return ptr[0] == 0 && ptr[1] == 0 ? BoxedDecimalZero : d;
}
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Features/Core/Portable/Debugging/DebugInformationReaderProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Debugging
{
/// <summary>
/// An abstraction of a symbol reader that provides a reader of Edit and Continue debug information.
/// Owns the underlying PDB reader.
/// </summary>
internal abstract class DebugInformationReaderProvider : IDisposable
{
private sealed class DummySymReaderMetadataProvider : ISymReaderMetadataProvider
{
public static readonly DummySymReaderMetadataProvider Instance = new();
public unsafe bool TryGetStandaloneSignature(int standaloneSignatureToken, out byte* signature, out int length)
=> throw ExceptionUtilities.Unreachable;
public bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes)
=> throw ExceptionUtilities.Unreachable;
public bool TryGetTypeReferenceInfo(int typeReferenceToken, out string namespaceName, out string typeName)
=> throw ExceptionUtilities.Unreachable;
}
private sealed class Portable : DebugInformationReaderProvider
{
private readonly MetadataReaderProvider _pdbReaderProvider;
public Portable(MetadataReaderProvider pdbReaderProvider)
=> _pdbReaderProvider = pdbReaderProvider;
public override EditAndContinueMethodDebugInfoReader CreateEditAndContinueMethodDebugInfoReader()
=> EditAndContinueMethodDebugInfoReader.Create(_pdbReaderProvider.GetMetadataReader());
public override void Dispose()
=> _pdbReaderProvider.Dispose();
}
private sealed class Native : DebugInformationReaderProvider
{
private readonly Stream _stream;
private readonly int _version;
private ISymUnmanagedReader5 _symReader;
public Native(Stream stream, ISymUnmanagedReader5 symReader, int version)
{
_stream = stream;
_symReader = symReader;
_version = version;
}
public override EditAndContinueMethodDebugInfoReader CreateEditAndContinueMethodDebugInfoReader()
=> EditAndContinueMethodDebugInfoReader.Create(_symReader, _version);
public override void Dispose()
{
_stream.Dispose();
var symReader = Interlocked.Exchange(ref _symReader, null);
if (symReader != null && Marshal.IsComObject(symReader))
{
Marshal.ReleaseComObject(symReader);
}
}
}
public abstract void Dispose();
/// <summary>
/// Creates EnC debug information reader.
/// </summary>
public abstract EditAndContinueMethodDebugInfoReader CreateEditAndContinueMethodDebugInfoReader();
/// <summary>
/// Creates <see cref="DebugInformationReaderProvider"/> from a stream of Portable or Windows PDB.
/// </summary>
/// <returns>
/// Provider instance, which keeps the <paramref name="stream"/> open until disposed.
/// </returns>
/// <remarks>
/// Requires Microsoft.DiaSymReader.Native.{platform}.dll to be available for reading Windows PDB.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="stream"/> does not support read and seek operations.</exception>
/// <exception cref="Exception">Error reading debug information from <paramref name="stream"/>.</exception>
public static DebugInformationReaderProvider CreateFromStream(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead || !stream.CanSeek)
{
throw new ArgumentException(FeaturesResources.StreamMustSupportReadAndSeek, nameof(stream));
}
var isPortable = stream.ReadByte() == 'B' && stream.ReadByte() == 'S' && stream.ReadByte() == 'J' && stream.ReadByte() == 'B';
stream.Position = 0;
if (isPortable)
{
return new Portable(MetadataReaderProvider.FromPortablePdbStream(stream));
}
// We can use DummySymReaderMetadataProvider since we do not need to decode signatures,
// which is the only operation SymReader needs the provider for.
return new Native(stream, SymUnmanagedReaderFactory.CreateReader<ISymUnmanagedReader5>(
stream, DummySymReaderMetadataProvider.Instance, SymUnmanagedReaderCreationOptions.UseAlternativeLoadPath), version: 1);
}
/// <summary>
/// Creates <see cref="DebugInformationReaderProvider"/> from a Portable PDB metadata reader provider.
/// </summary>
/// <returns>
/// Provider instance, which takes ownership of the <paramref name="metadataProvider"/> until disposed.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="metadataProvider"/> is null.</exception>
public static DebugInformationReaderProvider CreateFromMetadataReader(MetadataReaderProvider metadataProvider)
=> new Portable(metadataProvider ?? throw new ArgumentNullException(nameof(metadataProvider)));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Debugging
{
/// <summary>
/// An abstraction of a symbol reader that provides a reader of Edit and Continue debug information.
/// Owns the underlying PDB reader.
/// </summary>
internal abstract class DebugInformationReaderProvider : IDisposable
{
private sealed class DummySymReaderMetadataProvider : ISymReaderMetadataProvider
{
public static readonly DummySymReaderMetadataProvider Instance = new();
public unsafe bool TryGetStandaloneSignature(int standaloneSignatureToken, out byte* signature, out int length)
=> throw ExceptionUtilities.Unreachable;
public bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes)
=> throw ExceptionUtilities.Unreachable;
public bool TryGetTypeReferenceInfo(int typeReferenceToken, out string namespaceName, out string typeName)
=> throw ExceptionUtilities.Unreachable;
}
private sealed class Portable : DebugInformationReaderProvider
{
private readonly MetadataReaderProvider _pdbReaderProvider;
public Portable(MetadataReaderProvider pdbReaderProvider)
=> _pdbReaderProvider = pdbReaderProvider;
public override EditAndContinueMethodDebugInfoReader CreateEditAndContinueMethodDebugInfoReader()
=> EditAndContinueMethodDebugInfoReader.Create(_pdbReaderProvider.GetMetadataReader());
public override void Dispose()
=> _pdbReaderProvider.Dispose();
}
private sealed class Native : DebugInformationReaderProvider
{
private readonly Stream _stream;
private readonly int _version;
private ISymUnmanagedReader5 _symReader;
public Native(Stream stream, ISymUnmanagedReader5 symReader, int version)
{
_stream = stream;
_symReader = symReader;
_version = version;
}
public override EditAndContinueMethodDebugInfoReader CreateEditAndContinueMethodDebugInfoReader()
=> EditAndContinueMethodDebugInfoReader.Create(_symReader, _version);
public override void Dispose()
{
_stream.Dispose();
var symReader = Interlocked.Exchange(ref _symReader, null);
if (symReader != null && Marshal.IsComObject(symReader))
{
Marshal.ReleaseComObject(symReader);
}
}
}
public abstract void Dispose();
/// <summary>
/// Creates EnC debug information reader.
/// </summary>
public abstract EditAndContinueMethodDebugInfoReader CreateEditAndContinueMethodDebugInfoReader();
/// <summary>
/// Creates <see cref="DebugInformationReaderProvider"/> from a stream of Portable or Windows PDB.
/// </summary>
/// <returns>
/// Provider instance, which keeps the <paramref name="stream"/> open until disposed.
/// </returns>
/// <remarks>
/// Requires Microsoft.DiaSymReader.Native.{platform}.dll to be available for reading Windows PDB.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="stream"/> does not support read and seek operations.</exception>
/// <exception cref="Exception">Error reading debug information from <paramref name="stream"/>.</exception>
public static DebugInformationReaderProvider CreateFromStream(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead || !stream.CanSeek)
{
throw new ArgumentException(FeaturesResources.StreamMustSupportReadAndSeek, nameof(stream));
}
var isPortable = stream.ReadByte() == 'B' && stream.ReadByte() == 'S' && stream.ReadByte() == 'J' && stream.ReadByte() == 'B';
stream.Position = 0;
if (isPortable)
{
return new Portable(MetadataReaderProvider.FromPortablePdbStream(stream));
}
// We can use DummySymReaderMetadataProvider since we do not need to decode signatures,
// which is the only operation SymReader needs the provider for.
return new Native(stream, SymUnmanagedReaderFactory.CreateReader<ISymUnmanagedReader5>(
stream, DummySymReaderMetadataProvider.Instance, SymUnmanagedReaderCreationOptions.UseAlternativeLoadPath), version: 1);
}
/// <summary>
/// Creates <see cref="DebugInformationReaderProvider"/> from a Portable PDB metadata reader provider.
/// </summary>
/// <returns>
/// Provider instance, which takes ownership of the <paramref name="metadataProvider"/> until disposed.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="metadataProvider"/> is null.</exception>
public static DebugInformationReaderProvider CreateFromMetadataReader(MetadataReaderProvider metadataProvider)
=> new Portable(metadataProvider ?? throw new ArgumentNullException(nameof(metadataProvider)));
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/EditorFeatures/Core/SymbolSearch/SymbolSearchUpdateEngine.IOService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
namespace Microsoft.CodeAnalysis.SymbolSearch
{
internal partial class SymbolSearchUpdateEngine
{
private class IOService : IIOService
{
public void Create(DirectoryInfo directory) => directory.Create();
public void Delete(FileInfo file) => file.Delete();
public bool Exists(FileSystemInfo info) => info.Exists;
public byte[] ReadAllBytes(string path) => File.ReadAllBytes(path);
public void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) =>
File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
public void Move(string sourceFileName, string destinationFileName) =>
File.Move(sourceFileName, destinationFileName);
public void WriteAndFlushAllBytes(string path, byte[] bytes)
{
using var fileStream = new FileStream(path, FileMode.Create);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Flush(flushToDisk: true);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.IO;
namespace Microsoft.CodeAnalysis.SymbolSearch
{
internal partial class SymbolSearchUpdateEngine
{
private class IOService : IIOService
{
public void Create(DirectoryInfo directory) => directory.Create();
public void Delete(FileInfo file) => file.Delete();
public bool Exists(FileSystemInfo info) => info.Exists;
public byte[] ReadAllBytes(string path) => File.ReadAllBytes(path);
public void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors) =>
File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
public void Move(string sourceFileName, string destinationFileName) =>
File.Move(sourceFileName, destinationFileName);
public void WriteAndFlushAllBytes(string path, byte[] bytes)
{
using var fileStream = new FileStream(path, FileMode.Create);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Flush(flushToDisk: true);
}
}
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/CSharp/Portable/Syntax/CheckedStatementSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 CheckedStatementSyntax
{
public CheckedStatementSyntax Update(SyntaxToken keyword, BlockSyntax block)
=> Update(AttributeLists, keyword, block);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static CheckedStatementSyntax CheckedStatement(SyntaxKind kind, SyntaxToken keyword, BlockSyntax block)
=> CheckedStatement(kind, attributeLists: default, keyword, block);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 CheckedStatementSyntax
{
public CheckedStatementSyntax Update(SyntaxToken keyword, BlockSyntax block)
=> Update(AttributeLists, keyword, block);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static CheckedStatementSyntax CheckedStatement(SyntaxKind kind, SyntaxToken keyword, BlockSyntax block)
=> CheckedStatement(kind, attributeLists: default, keyword, block);
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/WithStatementSymbolsTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
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.ExtensionMethods
Public Class WithStatementSymbolsTests
Inherits BasicTestBase
<Fact()>
Public Sub LocalInEmptyWithStatementExpression()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression">
<file name="a.vb">
Module WithTestScoping
Sub Main()
Dim o1 As New Object()
With [#0 o1 0#]
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As System.Object", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub NestedWithWithLambdasAndObjectInitializers()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression">
<file name="a.vb">
Imports System
Structure SS1
Public A As String
Public B As String
End Structure
Structure SS2
Public X As SS1
Public Y As SS1
End Structure
Structure Clazz
Shared Sub Main(args() As String)
Dim t As New Clazz(1)
End Sub
Sub New(i As Integer)
Dim outer As New SS2
With outer
Dim a As New [#0 SS2 0#]() With {.X = Function() As SS1
With .Y
a.Y.B = a.Y.A
a.Y.A = "1"
End With
Return .Y
End Function.Invoke()}
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("SS2", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub LocalInEmptyWithStatementExpression_Struct()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression_Struct">
<file name="a.vb">
Structure STR
Public F As String
End Structure
Module WithTestScoping
Sub Main()
Dim o1 As New STR()
With [#0 o1 0#]
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As STR", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub LocalInWithStatementExpression()
Dim compilationDef =
<compilation name="LocalInWithStatementExpression">
<file name="a.vb">
Module WithTestScoping
Sub Main()
Dim o1 As New Object()
With [#0 o1 0#]
Dim o1 = Nothing
With [#1 o1 1#]
Dim o2 = Nothing
End With
With [#2 New Object() 2#]
Dim o1 As New Object()
Dim o2 = Nothing
End With
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes,
<errors>
BC30616: Variable 'o1' hides a variable in an enclosing block.
Dim o1 = Nothing
~~
BC30616: Variable 'o1' hides a variable in an enclosing block.
Dim o1 As New Object()
~~
</errors>)
Assert.Equal(3, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As System.Object", info0.Symbol.ToTestDisplayString())
Dim info1 = model.GetSemanticInfoSummary(DirectCast(nodes(1), ExpressionSyntax))
Assert.NotNull(info1.Symbol)
Assert.Equal("o1 As System.Object", info1.Symbol.ToTestDisplayString())
Assert.NotSame(info0.Symbol, info1.Symbol)
Dim info2 = model.GetSemanticInfoSummary(DirectCast(nodes(2), ExpressionSyntax))
Assert.NotNull(info2.Symbol)
Assert.Equal("Sub System.Object..ctor()", info2.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub NestedWithStatements()
Dim compilationDef =
<compilation name="NestedWithStatements">
<file name="a.vb">
Structure Clazz
Structure SS
Public FLD As String
End Structure
Public FLD As SS
Sub TEST()
With Me
With [#0 .FLD 0#]
Dim v As String = .GetType() .ToString()
End With
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("Clazz.FLD As Clazz.SS", info0.Symbol.ToTestDisplayString())
Dim systemObject = compilation.GetTypeByMetadataName("System.Object")
Dim conv = model.ClassifyConversion(DirectCast(nodes(0), ExpressionSyntax), systemObject)
Assert.True(conv.IsWidening)
End Sub
<Fact()>
Public Sub LocalInWithStatementExpression3()
Dim compilationDef =
<compilation name="LocalInWithStatementExpression3">
<file name="a.vb">
Structure Clazz
Structure SSS
Public FLD As String
End Structure
Structure SS
Public FS As SSS
End Structure
Public FLD As SS
Sub TEST()
With Me
With .FLD
With .FS
Dim v = [#0 .FLD 0#]
End With
End With
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("Clazz.SSS.FLD As System.String", info0.Symbol.ToTestDisplayString())
Dim systemObject = compilation.GetTypeByMetadataName("System.Object")
Dim conv = model.ClassifyConversion(DirectCast(nodes(0), ExpressionSyntax), systemObject)
Assert.True(conv.IsWidening)
End Sub
#Region "Utils"
Private Function Compile(text As XElement, ByRef tree As SyntaxTree, nodes As List(Of SyntaxNode), Optional errors As XElement = Nothing) As VisualBasicCompilation
Dim spans As New List(Of TextSpan)
ExtractTextIntervals(text, spans)
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(text, {SystemRef, SystemCoreRef, MsvbRef})
If errors Is Nothing Then
CompilationUtils.AssertNoErrors(compilation)
Else
CompilationUtils.AssertTheseDiagnostics(compilation, errors)
End If
tree = compilation.SyntaxTrees(0)
For Each span In spans
Dim stack As New Stack(Of SyntaxNode)
stack.Push(tree.GetRoot())
While stack.Count > 0
Dim node = stack.Pop()
If span.Contains(node.Span) Then
nodes.Add(node)
Exit While
End If
For Each child In node.ChildNodes
stack.Push(child)
Next
End While
Next
Return compilation
End Function
Private Shared Sub ExtractTextIntervals(text As XElement, nodes As List(Of TextSpan))
text.<file>.Value = text.<file>.Value.Trim().Replace(vbLf, vbCrLf)
Dim index As Integer = 0
Do
Dim startMarker = "[#" & index
Dim endMarker = index & "#]"
' opening '[#{0-9}'
Dim start = text.<file>.Value.IndexOf(startMarker, StringComparison.Ordinal)
If start < 0 Then
Exit Do
End If
' closing '{0-9}#]'
Dim [end] = text.<file>.Value.IndexOf(endMarker, StringComparison.Ordinal)
Assert.InRange([end], 0, Int32.MaxValue)
nodes.Add(New TextSpan(start, [end] - start + 3))
text.<file>.Value = text.<file>.Value.Replace(startMarker, " ").Replace(endMarker, " ")
index += 1
Assert.InRange(index, 0, 9)
Loop
End Sub
Private Shared Function GetNamedTypeSymbol(c As VisualBasicCompilation, namedTypeName As String, Optional fromCorLib As Boolean = False) As NamedTypeSymbol
Dim nameParts = namedTypeName.Split("."c)
Dim srcAssembly = DirectCast(c.Assembly, SourceAssemblySymbol)
Dim nsSymbol As NamespaceSymbol = (If(fromCorLib, srcAssembly.CorLibrary, srcAssembly)).GlobalNamespace
For Each ns In nameParts.Take(nameParts.Length - 1)
nsSymbol = DirectCast(nsSymbol.GetMember(ns), NamespaceSymbol)
Next
Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol)
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.Runtime.CompilerServices
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
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.ExtensionMethods
Public Class WithStatementSymbolsTests
Inherits BasicTestBase
<Fact()>
Public Sub LocalInEmptyWithStatementExpression()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression">
<file name="a.vb">
Module WithTestScoping
Sub Main()
Dim o1 As New Object()
With [#0 o1 0#]
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As System.Object", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub NestedWithWithLambdasAndObjectInitializers()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression">
<file name="a.vb">
Imports System
Structure SS1
Public A As String
Public B As String
End Structure
Structure SS2
Public X As SS1
Public Y As SS1
End Structure
Structure Clazz
Shared Sub Main(args() As String)
Dim t As New Clazz(1)
End Sub
Sub New(i As Integer)
Dim outer As New SS2
With outer
Dim a As New [#0 SS2 0#]() With {.X = Function() As SS1
With .Y
a.Y.B = a.Y.A
a.Y.A = "1"
End With
Return .Y
End Function.Invoke()}
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("SS2", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub LocalInEmptyWithStatementExpression_Struct()
Dim compilationDef =
<compilation name="LocalInEmptyWithStatementExpression_Struct">
<file name="a.vb">
Structure STR
Public F As String
End Structure
Module WithTestScoping
Sub Main()
Dim o1 As New STR()
With [#0 o1 0#]
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As STR", info0.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub LocalInWithStatementExpression()
Dim compilationDef =
<compilation name="LocalInWithStatementExpression">
<file name="a.vb">
Module WithTestScoping
Sub Main()
Dim o1 As New Object()
With [#0 o1 0#]
Dim o1 = Nothing
With [#1 o1 1#]
Dim o2 = Nothing
End With
With [#2 New Object() 2#]
Dim o1 As New Object()
Dim o2 = Nothing
End With
End With
End Sub
End Module
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes,
<errors>
BC30616: Variable 'o1' hides a variable in an enclosing block.
Dim o1 = Nothing
~~
BC30616: Variable 'o1' hides a variable in an enclosing block.
Dim o1 As New Object()
~~
</errors>)
Assert.Equal(3, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("o1 As System.Object", info0.Symbol.ToTestDisplayString())
Dim info1 = model.GetSemanticInfoSummary(DirectCast(nodes(1), ExpressionSyntax))
Assert.NotNull(info1.Symbol)
Assert.Equal("o1 As System.Object", info1.Symbol.ToTestDisplayString())
Assert.NotSame(info0.Symbol, info1.Symbol)
Dim info2 = model.GetSemanticInfoSummary(DirectCast(nodes(2), ExpressionSyntax))
Assert.NotNull(info2.Symbol)
Assert.Equal("Sub System.Object..ctor()", info2.Symbol.ToTestDisplayString())
End Sub
<Fact()>
Public Sub NestedWithStatements()
Dim compilationDef =
<compilation name="NestedWithStatements">
<file name="a.vb">
Structure Clazz
Structure SS
Public FLD As String
End Structure
Public FLD As SS
Sub TEST()
With Me
With [#0 .FLD 0#]
Dim v As String = .GetType() .ToString()
End With
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("Clazz.FLD As Clazz.SS", info0.Symbol.ToTestDisplayString())
Dim systemObject = compilation.GetTypeByMetadataName("System.Object")
Dim conv = model.ClassifyConversion(DirectCast(nodes(0), ExpressionSyntax), systemObject)
Assert.True(conv.IsWidening)
End Sub
<Fact()>
Public Sub LocalInWithStatementExpression3()
Dim compilationDef =
<compilation name="LocalInWithStatementExpression3">
<file name="a.vb">
Structure Clazz
Structure SSS
Public FLD As String
End Structure
Structure SS
Public FS As SSS
End Structure
Public FLD As SS
Sub TEST()
With Me
With .FLD
With .FS
Dim v = [#0 .FLD 0#]
End With
End With
End With
End Sub
End Structure
</file>
</compilation>
Dim tree As SyntaxTree = Nothing
Dim nodes As New List(Of SyntaxNode)
Dim compilation = Compile(compilationDef, tree, nodes)
Assert.Equal(1, nodes.Count)
Dim model = compilation.GetSemanticModel(tree)
Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax))
Assert.NotNull(info0.Symbol)
Assert.Equal("Clazz.SSS.FLD As System.String", info0.Symbol.ToTestDisplayString())
Dim systemObject = compilation.GetTypeByMetadataName("System.Object")
Dim conv = model.ClassifyConversion(DirectCast(nodes(0), ExpressionSyntax), systemObject)
Assert.True(conv.IsWidening)
End Sub
#Region "Utils"
Private Function Compile(text As XElement, ByRef tree As SyntaxTree, nodes As List(Of SyntaxNode), Optional errors As XElement = Nothing) As VisualBasicCompilation
Dim spans As New List(Of TextSpan)
ExtractTextIntervals(text, spans)
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(text, {SystemRef, SystemCoreRef, MsvbRef})
If errors Is Nothing Then
CompilationUtils.AssertNoErrors(compilation)
Else
CompilationUtils.AssertTheseDiagnostics(compilation, errors)
End If
tree = compilation.SyntaxTrees(0)
For Each span In spans
Dim stack As New Stack(Of SyntaxNode)
stack.Push(tree.GetRoot())
While stack.Count > 0
Dim node = stack.Pop()
If span.Contains(node.Span) Then
nodes.Add(node)
Exit While
End If
For Each child In node.ChildNodes
stack.Push(child)
Next
End While
Next
Return compilation
End Function
Private Shared Sub ExtractTextIntervals(text As XElement, nodes As List(Of TextSpan))
text.<file>.Value = text.<file>.Value.Trim().Replace(vbLf, vbCrLf)
Dim index As Integer = 0
Do
Dim startMarker = "[#" & index
Dim endMarker = index & "#]"
' opening '[#{0-9}'
Dim start = text.<file>.Value.IndexOf(startMarker, StringComparison.Ordinal)
If start < 0 Then
Exit Do
End If
' closing '{0-9}#]'
Dim [end] = text.<file>.Value.IndexOf(endMarker, StringComparison.Ordinal)
Assert.InRange([end], 0, Int32.MaxValue)
nodes.Add(New TextSpan(start, [end] - start + 3))
text.<file>.Value = text.<file>.Value.Replace(startMarker, " ").Replace(endMarker, " ")
index += 1
Assert.InRange(index, 0, 9)
Loop
End Sub
Private Shared Function GetNamedTypeSymbol(c As VisualBasicCompilation, namedTypeName As String, Optional fromCorLib As Boolean = False) As NamedTypeSymbol
Dim nameParts = namedTypeName.Split("."c)
Dim srcAssembly = DirectCast(c.Assembly, SourceAssemblySymbol)
Dim nsSymbol As NamespaceSymbol = (If(fromCorLib, srcAssembly.CorLibrary, srcAssembly)).GlobalNamespace
For Each ns In nameParts.Take(nameParts.Length - 1)
nsSymbol = DirectCast(nsSymbol.GetMember(ns), NamespaceSymbol)
Next
Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol)
End Function
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/VisualBasic/Portable/Binding/Binder_SelectCase.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
#Region "Bind select case statement"
Private Function BindSelectBlock(node As SelectBlockSyntax, diagnostics As BindingDiagnosticBag) As BoundStatement
Debug.Assert(node IsNot Nothing)
' Bind select expression
Dim selectExprStatementSyntax = node.SelectStatement
Dim expression = BindSelectExpression(selectExprStatementSyntax.Expression, diagnostics)
If expression.HasErrors Then
diagnostics = BindingDiagnosticBag.Discarded
End If
Dim exprPlaceHolder = New BoundRValuePlaceholder(selectExprStatementSyntax.Expression, expression.Type)
exprPlaceHolder.SetWasCompilerGenerated()
Dim expressionStmt = New BoundExpressionStatement(selectExprStatementSyntax, expression)
' Get the binder for the select block. This defines the exit label.
Dim selectBinder = GetBinder(DirectCast(node, VisualBasicSyntaxNode))
' Flag to determine if we need to generate switch table based code or If list based code.
' See OptimizeSelectStatement method for more details.
Dim recommendSwitchTable = False
' Bind case blocks.
Dim caseBlocks As ImmutableArray(Of BoundCaseBlock) = selectBinder.BindCaseBlocks(
node.CaseBlocks,
exprPlaceHolder,
convertCaseElements:=expression.Type.IsIntrinsicOrEnumType(),
recommendSwitchTable:=recommendSwitchTable,
diagnostics:=diagnostics)
' Create the bound node.
Return New BoundSelectStatement(node, expressionStmt, exprPlaceHolder, caseBlocks, recommendSwitchTable,
exitLabel:=selectBinder.GetExitLabel(SyntaxKind.ExitSelectStatement))
End Function
Private Function BindSelectExpression(node As ExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
' SPEC: A Select Case statement executes statements based on the value of an expression.
' SPEC: The expression must be classified as a value.
' We want to generate select case specific diagnostics if select expression is
' AddressOf expression or Lambda expression.
' For remaining expression kinds, bind the select expression as value.
' We also need to handle SyntaxKind.ParenthesizedExpression here.
' We might have a AddressOf expression or Lambda expression within a parenthesized expression.
' We want to generate ERRID.ERR_AddressOfInSelectCaseExpr/ERRID.ERR_LambdaInSelectCaseExpr for this case.
' See test BindingErrorTests.BC36635ERR_LambdaInSelectCaseExpr.
Dim errorId As ERRID = Nothing
Select Case node.Kind
Case SyntaxKind.ParenthesizedExpression
Dim parenthesizedExpr = DirectCast(node, ParenthesizedExpressionSyntax)
Dim boundExpression = BindSelectExpression(parenthesizedExpr.Expression, diagnostics)
Return New BoundParenthesized(node, boundExpression, boundExpression.Type)
Case SyntaxKind.AddressOfExpression
errorId = ERRID.ERR_AddressOfInSelectCaseExpr
Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression
errorId = ERRID.ERR_LambdaInSelectCaseExpr
End Select
Dim boundExpr = BindExpression(node, diagnostics)
If boundExpr.HasErrors() Then
boundExpr = MakeRValue(boundExpr, diagnostics)
ElseIf errorId <> Nothing Then
ReportDiagnostic(diagnostics, node, errorId)
boundExpr = MakeRValueAndIgnoreDiagnostics(boundExpr)
Else
boundExpr = MakeRValue(boundExpr, diagnostics)
End If
Return boundExpr
End Function
Private Function BindCaseBlocks(
caseBlocks As SyntaxList(Of CaseBlockSyntax),
selectExpression As BoundRValuePlaceholder,
convertCaseElements As Boolean,
ByRef recommendSwitchTable As Boolean,
diagnostics As BindingDiagnosticBag
) As ImmutableArray(Of BoundCaseBlock)
If Not caseBlocks.IsEmpty() Then
Dim caseBlocksBuilder = ArrayBuilder(Of BoundCaseBlock).GetInstance()
' Bind case blocks.
For Each caseBlock In caseBlocks
caseBlocksBuilder.Add(BindCaseBlock(caseBlock, selectExpression, convertCaseElements, diagnostics))
Next
Return OptimizeSelectStatement(selectExpression, caseBlocksBuilder, recommendSwitchTable, diagnostics)
End If
Return ImmutableArray(Of BoundCaseBlock).Empty
End Function
Private Function BindCaseBlock(
node As CaseBlockSyntax,
selectExpression As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseBlock
Dim caseStatement As BoundCaseStatement = BindCaseStatement(node.CaseStatement, selectExpression, convertCaseElements, diagnostics)
Dim statementsSyntax As SyntaxList(Of StatementSyntax) = node.Statements
Dim bodyBinder = GetBinder(statementsSyntax)
Dim body As BoundBlock = bodyBinder.BindBlock(node, statementsSyntax, diagnostics).MakeCompilerGenerated()
Return New BoundCaseBlock(node, caseStatement, body)
End Function
Private Function BindCaseStatement(
node As CaseStatementSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseStatement
Dim caseClauses As ImmutableArray(Of BoundCaseClause)
If node.Kind = SyntaxKind.CaseStatement Then
Dim caseClauseBuilder = ArrayBuilder(Of BoundCaseClause).GetInstance()
' Bind case clauses.
For Each caseClause In node.Cases
caseClauseBuilder.Add(BindCaseClause(caseClause, selectExpressionOpt, convertCaseElements, diagnostics))
Next
caseClauses = caseClauseBuilder.ToImmutableAndFree()
Else
Debug.Assert(node.Kind = SyntaxKind.CaseElseStatement)
caseClauses = ImmutableArray(Of BoundCaseClause).Empty
End If
Return New BoundCaseStatement(node, caseClauses, conditionOpt:=Nothing)
End Function
Private Function BindCaseClause(
node As CaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
Select Case node.Kind
Case SyntaxKind.CaseEqualsClause, SyntaxKind.CaseNotEqualsClause,
SyntaxKind.CaseGreaterThanClause, SyntaxKind.CaseGreaterThanOrEqualClause,
SyntaxKind.CaseLessThanClause, SyntaxKind.CaseLessThanOrEqualClause
Return BindRelationalCaseClause(DirectCast(node, RelationalCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case SyntaxKind.SimpleCaseClause
Return BindSimpleCaseClause(DirectCast(node, SimpleCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case SyntaxKind.RangeCaseClause
Return BindRangeCaseClause(DirectCast(node, RangeCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
Private Function BindRelationalCaseClause(
node As RelationalCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: A Case clause may take two forms.
' SPEC: One form is an optional Is keyword, a comparison operator, and an expression.
' SPEC: The expression is converted to the type of the Select expression;
' SPEC: if the expression is not implicitly convertible to the type of
' SPEC: the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the comparison operator is Op,
' SPEC: and the Case expression is E1, the case is evaluated as E OP E1.
' SPEC: The operator must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
' Bind relational case clause as binary operator: E OP E1.
' BindBinaryOperator will generate the appropriate diagnostics.
Debug.Assert(SyntaxFacts.IsRelationalOperator(node.OperatorToken.Kind) OrElse node.ContainsDiagnostics)
Dim operatorKind As BinaryOperatorKind
Select Case node.Kind
Case SyntaxKind.CaseEqualsClause : operatorKind = BinaryOperatorKind.Equals
Case SyntaxKind.CaseNotEqualsClause : operatorKind = BinaryOperatorKind.NotEquals
Case SyntaxKind.CaseLessThanOrEqualClause : operatorKind = BinaryOperatorKind.LessThanOrEqual
Case SyntaxKind.CaseGreaterThanOrEqualClause : operatorKind = BinaryOperatorKind.GreaterThanOrEqual
Case SyntaxKind.CaseLessThanClause : operatorKind = BinaryOperatorKind.LessThan
Case SyntaxKind.CaseGreaterThanClause : operatorKind = BinaryOperatorKind.GreaterThan
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
Dim conditionOpt As BoundExpression = Nothing
Dim operandE1 As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.Value,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=node.OperatorToken.Kind,
operatorKind:=operatorKind,
convertCaseElements:=convertCaseElements,
conditionOpt:=conditionOpt,
diagnostics:=diagnostics)
Return New BoundRelationalCaseClause(node, operatorKind, operandE1, conditionOpt)
End Function
Private Function BindSimpleCaseClause(
node As SimpleCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: The other form is an expression optionally followed by the keyword To and
' SPEC: a second expression. Both expressions are converted to the type of the
' SPEC: Select expression; if either expression is not implicitly convertible to
' SPEC: the type of the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the first Case expression is E1,
' SPEC: and the second Case expression is E2, the Case is evaluated either
' SPEC: as E = E1 (if no E2 is specified) or (E >= E1) And (E <= E2).
' SPEC: The operators must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
Dim conditionOpt As BoundExpression = Nothing
' Bind the Case clause as E = E1 (no E2 is specified)
Dim value As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.Value,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.EqualsToken,
operatorKind:=BinaryOperatorKind.Equals,
convertCaseElements:=convertCaseElements,
conditionOpt:=conditionOpt,
diagnostics:=diagnostics)
Return New BoundSimpleCaseClause(node, value, conditionOpt)
End Function
Private Function BindRangeCaseClause(
node As RangeCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: The other form is an expression optionally followed by the keyword To and
' SPEC: a second expression. Both expressions are converted to the type of the
' SPEC: Select expression; if either expression is not implicitly convertible to
' SPEC: the type of the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the first Case expression is E1,
' SPEC: and the second Case expression is E2, the Case is evaluated either
' SPEC: as E = E1 (if no E2 is specified) or (E >= E1) And (E <= E2).
' SPEC: The operators must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
Dim lowerBoundConditionOpt As BoundExpression = Nothing
' Bind case clause lower bound value (E >= E1)
Dim lowerBound As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.LowerBound,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.GreaterThanEqualsToken,
operatorKind:=BinaryOperatorKind.GreaterThanOrEqual,
convertCaseElements:=convertCaseElements,
conditionOpt:=lowerBoundConditionOpt,
diagnostics:=diagnostics)
' Bind case clause upper bound value (E <= E2)
Dim upperBoundConditionOpt As BoundExpression = Nothing
Dim upperBound As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.UpperBound,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.LessThanEqualsToken,
operatorKind:=BinaryOperatorKind.LessThanOrEqual,
convertCaseElements:=convertCaseElements,
conditionOpt:=upperBoundConditionOpt,
diagnostics:=diagnostics)
Return New BoundRangeCaseClause(node, lowerBound, upperBound, lowerBoundConditionOpt, upperBoundConditionOpt)
End Function
Private Function BindCaseClauseExpression(
expressionSyntax As ExpressionSyntax,
caseClauseSyntax As CaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
operatorTokenKind As SyntaxKind,
operatorKind As BinaryOperatorKind,
convertCaseElements As Boolean,
ByRef conditionOpt As BoundExpression,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim caseExpr As BoundExpression = BindValue(expressionSyntax, diagnostics)
If selectExpressionOpt Is Nothing Then
' In error scenarios, such as a Case statement outside of a
' Select statement, the Select expression may be Nothing.
conditionOpt = Nothing
Return MakeRValue(caseExpr, diagnostics)
End If
If convertCaseElements AndAlso caseExpr.Type.IsIntrinsicOrEnumType() Then
' SPEC: The expression is converted to the type of the Select expression;
' SPEC: if the expression is not implicitly convertible to the type of the Select expression, a compile-time error occurs.
Debug.Assert(selectExpressionOpt.Type IsNot Nothing)
Return ApplyImplicitConversion(expressionSyntax, selectExpressionOpt.Type, caseExpr, diagnostics)
Else
' SPEC: If the Select expression is E, the comparison operator is Op,
' SPEC: and the Case expression is E1, the case is evaluated as E OP E1.
' Bind binary operator "selectExpression OP caseExpr" to generate necessary diagnostics.
conditionOpt = BindBinaryOperator(
node:=caseClauseSyntax,
left:=selectExpressionOpt,
right:=caseExpr,
operatorTokenKind:=operatorTokenKind,
preliminaryOperatorKind:=operatorKind,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
Return Nothing
End If
End Function
#Region "Helper methods for Binding Select case statement"
' This function is identical to the Semantics::OptimizeSelectStatement in native compiler.
' It performs two primary tasks:
' 1) Determines what kind of byte codes will be used for select: Switch Table or If List.
' Ideally we would like to delay these kind of optimizations till rewriting/emit phase.
' However, the computation of the case statement conditional would be redundant if
' we are eventually going to emit Switch table based byte code. Hence we match the
' native compiler behavior and check RecommendSwitchTable() here and store this
' value in the BoundSelectStatement node to be reused in the rewriter.
' 2) If we are going to generate If list based byte code, this function computes the
' conditional expression for case statements and stores it in the BoundCaseStatement nodes.
' Condition for each case statement "Case clause1, clause2, ..., clauseN"
' is computed as "clause1 OrElse clause2 OrElse ... OrElse clauseN" expression.
Private Function OptimizeSelectStatement(
selectExpression As BoundRValuePlaceholder,
caseBlockBuilder As ArrayBuilder(Of BoundCaseBlock),
ByRef generateSwitchTable As Boolean,
diagnostics As BindingDiagnosticBag
) As ImmutableArray(Of BoundCaseBlock)
Debug.Assert(Not selectExpression.HasErrors)
generateSwitchTable = RecommendSwitchTable(selectExpression, caseBlockBuilder, diagnostics)
' CONSIDER: Do we need to compute the case statement conditional expression
' CONSIDER: even for generateSwitchTable case? We might want to do so to
' CONSIDER: maintain consistency of bound nodes coming out of the binder.
' CONSIDER: With the current design, value of BoundCaseStatement.ConditionOpt field
' CONSIDER: is dependent on the value of generateSwitchTable.
If Not generateSwitchTable AndAlso caseBlockBuilder.Any() Then
Dim booleanType = GetSpecialType(SpecialType.System_Boolean, selectExpression.Syntax, diagnostics)
Dim caseClauseBuilder = ArrayBuilder(Of BoundCaseClause).GetInstance()
For index = 0 To caseBlockBuilder.Count - 1
Dim caseBlock = caseBlockBuilder(index)
If caseBlock.Syntax.Kind <> SyntaxKind.CaseElseBlock AndAlso
Not caseBlock.CaseStatement.Syntax.IsMissing Then
Dim caseStatement = caseBlock.CaseStatement
Dim caseStatementSyntax = caseStatement.Syntax
Dim caseStatementCondition As BoundExpression = Nothing
Debug.Assert(caseStatement.CaseClauses.Any())
Dim clausesChanged = False
' Compute conditional expression for case statement
For Each caseClause In caseStatement.CaseClauses
Dim clauseCondition As BoundExpression = Nothing
' Compute conditional expression for case clause, if not already computed.
Dim newCaseClause = ComputeCaseClauseCondition(caseClause, clauseCondition, selectExpression, diagnostics)
caseClauseBuilder.Add(newCaseClause)
clausesChanged = clausesChanged OrElse Not newCaseClause.Equals(caseClause)
Debug.Assert(clauseCondition IsNot Nothing)
If caseStatementCondition Is Nothing Then
caseStatementCondition = clauseCondition
Else
' caseStatementCondition = caseStatementCondition OrElse clauseCondition
caseStatementCondition = BindBinaryOperator(
node:=caseStatementSyntax,
left:=caseStatementCondition,
right:=clauseCondition,
operatorTokenKind:=SyntaxKind.OrElseKeyword,
preliminaryOperatorKind:=BinaryOperatorKind.OrElse,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
Next
Dim newCaseClauses As ImmutableArray(Of BoundCaseClause)
If clausesChanged Then
newCaseClauses = caseClauseBuilder.ToImmutable()
Else
newCaseClauses = caseStatement.CaseClauses
End If
caseClauseBuilder.Clear()
caseStatementCondition = ApplyImplicitConversion(caseStatementCondition.Syntax, booleanType, caseStatementCondition, diagnostics:=diagnostics, isOperandOfConditionalBranch:=True)
caseStatement = caseStatement.Update(newCaseClauses, caseStatementCondition)
caseBlockBuilder(index) = caseBlock.Update(caseStatement, caseBlock.Body)
End If
Next
caseClauseBuilder.Free()
End If
Return caseBlockBuilder.ToImmutableAndFree()
End Function
Private Function ComputeCaseClauseCondition(caseClause As BoundCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Select Case caseClause.Kind
Case BoundKind.RelationalCaseClause
Return ComputeRelationalCaseClauseCondition(DirectCast(caseClause, BoundRelationalCaseClause), conditionOpt, selectExpression, diagnostics)
Case BoundKind.SimpleCaseClause
Return ComputeSimpleCaseClauseCondition(DirectCast(caseClause, BoundSimpleCaseClause), conditionOpt, selectExpression, diagnostics)
Case BoundKind.RangeCaseClause
Return ComputeRangeCaseClauseCondition(DirectCast(caseClause, BoundRangeCaseClause), conditionOpt, selectExpression, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
End Select
End Function
Private Function ComputeRelationalCaseClauseCondition(boundClause As BoundRelationalCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Dim syntax = DirectCast(boundClause.Syntax, RelationalCaseClauseSyntax)
' Exactly one of the operand or condition must be non-null
Debug.Assert(boundClause.ConditionOpt IsNot Nothing Xor boundClause.ValueOpt IsNot Nothing)
conditionOpt = If(boundClause.ConditionOpt, BindBinaryOperator(node:=syntax,
left:=selectExpression,
right:=boundClause.ValueOpt,
operatorTokenKind:=syntax.OperatorToken.Kind,
preliminaryOperatorKind:=boundClause.OperatorKind,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated())
Return boundClause.Update(boundClause.OperatorKind, valueOpt:=Nothing, conditionOpt:=conditionOpt)
End Function
Private Function ComputeSimpleCaseClauseCondition(boundClause As BoundSimpleCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
' Exactly one of the value or condition must be non-null
Debug.Assert(boundClause.ConditionOpt IsNot Nothing Xor boundClause.ValueOpt IsNot Nothing)
conditionOpt = If(boundClause.ConditionOpt, BindBinaryOperator(node:=boundClause.Syntax,
left:=selectExpression,
right:=boundClause.ValueOpt,
operatorTokenKind:=SyntaxKind.EqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.Equals,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated())
Return boundClause.Update(valueOpt:=Nothing, conditionOpt:=conditionOpt)
End Function
Private Function ComputeRangeCaseClauseCondition(boundClause As BoundRangeCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Dim syntax = boundClause.Syntax
' Exactly one of the LowerBoundOpt or LowerBoundConditionOpt must be non-null
Debug.Assert(boundClause.LowerBoundOpt IsNot Nothing Xor boundClause.LowerBoundConditionOpt IsNot Nothing)
Dim lowerBoundConditionOpt = boundClause.LowerBoundConditionOpt
If lowerBoundConditionOpt Is Nothing Then
lowerBoundConditionOpt = BindBinaryOperator(
node:=boundClause.Syntax,
left:=selectExpression,
right:=boundClause.LowerBoundOpt,
operatorTokenKind:=SyntaxKind.GreaterThanEqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.GreaterThanOrEqual,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
' Exactly one of the UpperBoundOpt or UpperBoundConditionOpt must be non-null
Debug.Assert(boundClause.UpperBoundOpt IsNot Nothing Xor boundClause.UpperBoundConditionOpt IsNot Nothing)
Dim upperBoundConditionOpt = boundClause.UpperBoundConditionOpt
If upperBoundConditionOpt Is Nothing Then
upperBoundConditionOpt = BindBinaryOperator(
node:=syntax,
left:=selectExpression,
right:=boundClause.UpperBoundOpt,
operatorTokenKind:=SyntaxKind.LessThanEqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.LessThanOrEqual,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
conditionOpt = BindBinaryOperator(
node:=syntax,
left:=lowerBoundConditionOpt,
right:=upperBoundConditionOpt,
operatorTokenKind:=SyntaxKind.AndAlsoKeyword,
preliminaryOperatorKind:=BinaryOperatorKind.AndAlso,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
Return boundClause.Update(lowerBoundOpt:=Nothing, upperBoundOpt:=Nothing, lowerBoundConditionOpt:=lowerBoundConditionOpt, upperBoundConditionOpt:=upperBoundConditionOpt)
End Function
' Helper method to determine if we must rewrite the select case statement as an IF list or a SWITCH table
Private Function RecommendSwitchTable(selectExpr As BoundRValuePlaceholder, caseBlocks As ArrayBuilder(Of BoundCaseBlock), diagnostics As BindingDiagnosticBag) As Boolean
' We can rewrite select case statement as an IF list or a SWITCH table
' This function determines which method to use.
' The conditions for choosing the SWITCH table are:
' select case expression type must be integral/boolean/string (see TypeSymbolExtensions.IsValidTypeForSwitchTable())
' no "Is <relop>" cases, except for <relop> = BinaryOperatorKind.Equals
' no "<lb> To <ub>" cases for string type
' for integral/boolean type, case values must be (or expand to, as in ranges) integer constants
' for string type, all case values must be string constants and OptionCompareText must be False.
' beneficial over IF lists (as per a threshold on size ratio)
' ranges must have lower bound first
' We also generate warnings for Invalid range clauses in this function.
' Ideally we would like to generate them in BindRangeCaseClause.
' However, Dev10 doesn't do this check individually for each CaseClause.
' It is performed only if bounds for all clauses in the Select are integer constants and
' all clauses are either range clauses or equality clause.
' Doing this differently will produce warnings in more scenarios - breaking change.
If Not caseBlocks.Any() OrElse Not selectExpr.Type.IsValidTypeForSwitchTable() Then
Return False
End If
Dim isSelectExprStringType = selectExpr.Type.IsStringType
If isSelectExprStringType AndAlso OptionCompareText Then
Return False
End If
Dim recommendSwitch = True
For Each caseBlock In caseBlocks
For Each caseClause In caseBlock.CaseStatement.CaseClauses
Select Case caseClause.Kind
Case BoundKind.RelationalCaseClause
Dim relationalClause = DirectCast(caseClause, BoundRelationalCaseClause)
' Exactly one of the operand or condition must be non-null
Debug.Assert(relationalClause.ValueOpt IsNot Nothing Xor relationalClause.ConditionOpt IsNot Nothing)
Dim operand = relationalClause.ValueOpt
If operand Is Nothing OrElse
relationalClause.OperatorKind <> BinaryOperatorKind.Equals OrElse
operand.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(operand.ConstantValueOpt) Then
Return False
End If
Case BoundKind.RangeCaseClause
' TODO: RecommendSwitchTable for Range clause.
' TODO: If we decide to implement it we will need to
' TODO: add heuristic to determine when the range is
' TODO: big enough to prefer IF lists over SWITCH table.
' TODO: We will also need to add logic in the emitter
' TODO: to iterate through ConstantValues in a range.
' For now we use IF lists if we encounter BoundRangeCaseClause
Dim rangeCaseClause = DirectCast(caseClause, BoundRangeCaseClause)
' Exactly one of the LowerBoundOpt or LowerBoundConditionOpt must be non-null
Debug.Assert(rangeCaseClause.LowerBoundOpt IsNot Nothing Xor rangeCaseClause.LowerBoundConditionOpt IsNot Nothing)
' Exactly one of the UpperBoundOpt or UpperBoundConditionOpt must be non-null
Debug.Assert(rangeCaseClause.UpperBoundOpt IsNot Nothing Xor rangeCaseClause.UpperBoundConditionOpt IsNot Nothing)
Dim lowerBound = rangeCaseClause.LowerBoundOpt
Dim upperBound = rangeCaseClause.UpperBoundOpt
If lowerBound Is Nothing OrElse
upperBound Is Nothing OrElse
lowerBound.ConstantValueOpt Is Nothing OrElse
upperBound.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(lowerBound.ConstantValueOpt) OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(upperBound.ConstantValueOpt) Then
Return False
End If
recommendSwitch = False
Case Else
Dim simpleCaseClause = DirectCast(caseClause, BoundSimpleCaseClause)
' Exactly one of the value or condition must be non-null
Debug.Assert(simpleCaseClause.ValueOpt IsNot Nothing Xor simpleCaseClause.ConditionOpt IsNot Nothing)
Dim value = simpleCaseClause.ValueOpt
If value Is Nothing OrElse
value.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(value.ConstantValueOpt) Then
Return False
End If
End Select
Next
Next
' TODO: beneficial over IF lists (as per a threshold on size ratio)
Return Not ReportInvalidSelectCaseRange(caseBlocks, diagnostics) AndAlso recommendSwitch
End Function
' Function reports WRN_SelectCaseInvalidRange for any invalid select case range.
' Returns True if an invalid range was found, False otherwise.
Private Function ReportInvalidSelectCaseRange(caseBlocks As ArrayBuilder(Of BoundCaseBlock), diagnostics As BindingDiagnosticBag) As Boolean
For Each caseBlock In caseBlocks
For Each caseClause In caseBlock.CaseStatement.CaseClauses
Select Case caseClause.Kind
Case BoundKind.RangeCaseClause
Dim rangeCaseClause = DirectCast(caseClause, BoundRangeCaseClause)
Dim lowerBound = rangeCaseClause.LowerBoundOpt
Dim upperBound = rangeCaseClause.UpperBoundOpt
Debug.Assert(lowerBound IsNot Nothing)
Debug.Assert(lowerBound.ConstantValueOpt IsNot Nothing)
Debug.Assert(upperBound IsNot Nothing)
Debug.Assert(upperBound.ConstantValueOpt IsNot Nothing)
Debug.Assert(rangeCaseClause.LowerBoundConditionOpt Is Nothing)
Debug.Assert(rangeCaseClause.UpperBoundConditionOpt Is Nothing)
If IsInvalidSelectCaseRange(lowerBound.ConstantValueOpt, upperBound.ConstantValueOpt) Then
ReportDiagnostic(diagnostics, rangeCaseClause.Syntax, ERRID.WRN_SelectCaseInvalidRange)
Return True
End If
End Select
Next
Next
Return False
End Function
Private Shared Function IsInvalidSelectCaseRange(lbConstantValue As ConstantValue, ubConstantValue As ConstantValue) As Boolean
Debug.Assert(lbConstantValue IsNot Nothing)
Debug.Assert(ubConstantValue IsNot Nothing)
Debug.Assert(lbConstantValue.SpecialType = ubConstantValue.SpecialType)
Select Case lbConstantValue.SpecialType
Case SpecialType.System_Boolean,
SpecialType.System_Byte,
SpecialType.System_UInt16,
SpecialType.System_UInt32,
SpecialType.System_UInt64
Return lbConstantValue.UInt64Value > ubConstantValue.UInt64Value
Case SpecialType.System_SByte,
SpecialType.System_Int16,
SpecialType.System_Int32,
SpecialType.System_Int64,
SpecialType.System_Char
Return lbConstantValue.Int64Value > ubConstantValue.Int64Value
Case SpecialType.System_Single,
SpecialType.System_Double
Return lbConstantValue.DoubleValue > ubConstantValue.DoubleValue
Case SpecialType.System_Decimal
Return lbConstantValue.DecimalValue > ubConstantValue.DecimalValue
Case Else
Return False
End Select
End Function
#End Region
#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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
#Region "Bind select case statement"
Private Function BindSelectBlock(node As SelectBlockSyntax, diagnostics As BindingDiagnosticBag) As BoundStatement
Debug.Assert(node IsNot Nothing)
' Bind select expression
Dim selectExprStatementSyntax = node.SelectStatement
Dim expression = BindSelectExpression(selectExprStatementSyntax.Expression, diagnostics)
If expression.HasErrors Then
diagnostics = BindingDiagnosticBag.Discarded
End If
Dim exprPlaceHolder = New BoundRValuePlaceholder(selectExprStatementSyntax.Expression, expression.Type)
exprPlaceHolder.SetWasCompilerGenerated()
Dim expressionStmt = New BoundExpressionStatement(selectExprStatementSyntax, expression)
' Get the binder for the select block. This defines the exit label.
Dim selectBinder = GetBinder(DirectCast(node, VisualBasicSyntaxNode))
' Flag to determine if we need to generate switch table based code or If list based code.
' See OptimizeSelectStatement method for more details.
Dim recommendSwitchTable = False
' Bind case blocks.
Dim caseBlocks As ImmutableArray(Of BoundCaseBlock) = selectBinder.BindCaseBlocks(
node.CaseBlocks,
exprPlaceHolder,
convertCaseElements:=expression.Type.IsIntrinsicOrEnumType(),
recommendSwitchTable:=recommendSwitchTable,
diagnostics:=diagnostics)
' Create the bound node.
Return New BoundSelectStatement(node, expressionStmt, exprPlaceHolder, caseBlocks, recommendSwitchTable,
exitLabel:=selectBinder.GetExitLabel(SyntaxKind.ExitSelectStatement))
End Function
Private Function BindSelectExpression(node As ExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression
' SPEC: A Select Case statement executes statements based on the value of an expression.
' SPEC: The expression must be classified as a value.
' We want to generate select case specific diagnostics if select expression is
' AddressOf expression or Lambda expression.
' For remaining expression kinds, bind the select expression as value.
' We also need to handle SyntaxKind.ParenthesizedExpression here.
' We might have a AddressOf expression or Lambda expression within a parenthesized expression.
' We want to generate ERRID.ERR_AddressOfInSelectCaseExpr/ERRID.ERR_LambdaInSelectCaseExpr for this case.
' See test BindingErrorTests.BC36635ERR_LambdaInSelectCaseExpr.
Dim errorId As ERRID = Nothing
Select Case node.Kind
Case SyntaxKind.ParenthesizedExpression
Dim parenthesizedExpr = DirectCast(node, ParenthesizedExpressionSyntax)
Dim boundExpression = BindSelectExpression(parenthesizedExpr.Expression, diagnostics)
Return New BoundParenthesized(node, boundExpression, boundExpression.Type)
Case SyntaxKind.AddressOfExpression
errorId = ERRID.ERR_AddressOfInSelectCaseExpr
Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression
errorId = ERRID.ERR_LambdaInSelectCaseExpr
End Select
Dim boundExpr = BindExpression(node, diagnostics)
If boundExpr.HasErrors() Then
boundExpr = MakeRValue(boundExpr, diagnostics)
ElseIf errorId <> Nothing Then
ReportDiagnostic(diagnostics, node, errorId)
boundExpr = MakeRValueAndIgnoreDiagnostics(boundExpr)
Else
boundExpr = MakeRValue(boundExpr, diagnostics)
End If
Return boundExpr
End Function
Private Function BindCaseBlocks(
caseBlocks As SyntaxList(Of CaseBlockSyntax),
selectExpression As BoundRValuePlaceholder,
convertCaseElements As Boolean,
ByRef recommendSwitchTable As Boolean,
diagnostics As BindingDiagnosticBag
) As ImmutableArray(Of BoundCaseBlock)
If Not caseBlocks.IsEmpty() Then
Dim caseBlocksBuilder = ArrayBuilder(Of BoundCaseBlock).GetInstance()
' Bind case blocks.
For Each caseBlock In caseBlocks
caseBlocksBuilder.Add(BindCaseBlock(caseBlock, selectExpression, convertCaseElements, diagnostics))
Next
Return OptimizeSelectStatement(selectExpression, caseBlocksBuilder, recommendSwitchTable, diagnostics)
End If
Return ImmutableArray(Of BoundCaseBlock).Empty
End Function
Private Function BindCaseBlock(
node As CaseBlockSyntax,
selectExpression As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseBlock
Dim caseStatement As BoundCaseStatement = BindCaseStatement(node.CaseStatement, selectExpression, convertCaseElements, diagnostics)
Dim statementsSyntax As SyntaxList(Of StatementSyntax) = node.Statements
Dim bodyBinder = GetBinder(statementsSyntax)
Dim body As BoundBlock = bodyBinder.BindBlock(node, statementsSyntax, diagnostics).MakeCompilerGenerated()
Return New BoundCaseBlock(node, caseStatement, body)
End Function
Private Function BindCaseStatement(
node As CaseStatementSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseStatement
Dim caseClauses As ImmutableArray(Of BoundCaseClause)
If node.Kind = SyntaxKind.CaseStatement Then
Dim caseClauseBuilder = ArrayBuilder(Of BoundCaseClause).GetInstance()
' Bind case clauses.
For Each caseClause In node.Cases
caseClauseBuilder.Add(BindCaseClause(caseClause, selectExpressionOpt, convertCaseElements, diagnostics))
Next
caseClauses = caseClauseBuilder.ToImmutableAndFree()
Else
Debug.Assert(node.Kind = SyntaxKind.CaseElseStatement)
caseClauses = ImmutableArray(Of BoundCaseClause).Empty
End If
Return New BoundCaseStatement(node, caseClauses, conditionOpt:=Nothing)
End Function
Private Function BindCaseClause(
node As CaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
Select Case node.Kind
Case SyntaxKind.CaseEqualsClause, SyntaxKind.CaseNotEqualsClause,
SyntaxKind.CaseGreaterThanClause, SyntaxKind.CaseGreaterThanOrEqualClause,
SyntaxKind.CaseLessThanClause, SyntaxKind.CaseLessThanOrEqualClause
Return BindRelationalCaseClause(DirectCast(node, RelationalCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case SyntaxKind.SimpleCaseClause
Return BindSimpleCaseClause(DirectCast(node, SimpleCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case SyntaxKind.RangeCaseClause
Return BindRangeCaseClause(DirectCast(node, RangeCaseClauseSyntax), selectExpressionOpt, convertCaseElements, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
Private Function BindRelationalCaseClause(
node As RelationalCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: A Case clause may take two forms.
' SPEC: One form is an optional Is keyword, a comparison operator, and an expression.
' SPEC: The expression is converted to the type of the Select expression;
' SPEC: if the expression is not implicitly convertible to the type of
' SPEC: the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the comparison operator is Op,
' SPEC: and the Case expression is E1, the case is evaluated as E OP E1.
' SPEC: The operator must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
' Bind relational case clause as binary operator: E OP E1.
' BindBinaryOperator will generate the appropriate diagnostics.
Debug.Assert(SyntaxFacts.IsRelationalOperator(node.OperatorToken.Kind) OrElse node.ContainsDiagnostics)
Dim operatorKind As BinaryOperatorKind
Select Case node.Kind
Case SyntaxKind.CaseEqualsClause : operatorKind = BinaryOperatorKind.Equals
Case SyntaxKind.CaseNotEqualsClause : operatorKind = BinaryOperatorKind.NotEquals
Case SyntaxKind.CaseLessThanOrEqualClause : operatorKind = BinaryOperatorKind.LessThanOrEqual
Case SyntaxKind.CaseGreaterThanOrEqualClause : operatorKind = BinaryOperatorKind.GreaterThanOrEqual
Case SyntaxKind.CaseLessThanClause : operatorKind = BinaryOperatorKind.LessThan
Case SyntaxKind.CaseGreaterThanClause : operatorKind = BinaryOperatorKind.GreaterThan
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
Dim conditionOpt As BoundExpression = Nothing
Dim operandE1 As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.Value,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=node.OperatorToken.Kind,
operatorKind:=operatorKind,
convertCaseElements:=convertCaseElements,
conditionOpt:=conditionOpt,
diagnostics:=diagnostics)
Return New BoundRelationalCaseClause(node, operatorKind, operandE1, conditionOpt)
End Function
Private Function BindSimpleCaseClause(
node As SimpleCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: The other form is an expression optionally followed by the keyword To and
' SPEC: a second expression. Both expressions are converted to the type of the
' SPEC: Select expression; if either expression is not implicitly convertible to
' SPEC: the type of the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the first Case expression is E1,
' SPEC: and the second Case expression is E2, the Case is evaluated either
' SPEC: as E = E1 (if no E2 is specified) or (E >= E1) And (E <= E2).
' SPEC: The operators must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
Dim conditionOpt As BoundExpression = Nothing
' Bind the Case clause as E = E1 (no E2 is specified)
Dim value As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.Value,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.EqualsToken,
operatorKind:=BinaryOperatorKind.Equals,
convertCaseElements:=convertCaseElements,
conditionOpt:=conditionOpt,
diagnostics:=diagnostics)
Return New BoundSimpleCaseClause(node, value, conditionOpt)
End Function
Private Function BindRangeCaseClause(
node As RangeCaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
convertCaseElements As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundCaseClause
' SPEC: The other form is an expression optionally followed by the keyword To and
' SPEC: a second expression. Both expressions are converted to the type of the
' SPEC: Select expression; if either expression is not implicitly convertible to
' SPEC: the type of the Select expression, a compile-time error occurs.
' SPEC: If the Select expression is E, the first Case expression is E1,
' SPEC: and the second Case expression is E2, the Case is evaluated either
' SPEC: as E = E1 (if no E2 is specified) or (E >= E1) And (E <= E2).
' SPEC: The operators must be valid for the types of the two expressions;
' SPEC: otherwise a compile-time error occurs.
Dim lowerBoundConditionOpt As BoundExpression = Nothing
' Bind case clause lower bound value (E >= E1)
Dim lowerBound As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.LowerBound,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.GreaterThanEqualsToken,
operatorKind:=BinaryOperatorKind.GreaterThanOrEqual,
convertCaseElements:=convertCaseElements,
conditionOpt:=lowerBoundConditionOpt,
diagnostics:=diagnostics)
' Bind case clause upper bound value (E <= E2)
Dim upperBoundConditionOpt As BoundExpression = Nothing
Dim upperBound As BoundExpression = BindCaseClauseExpression(
expressionSyntax:=node.UpperBound,
caseClauseSyntax:=node,
selectExpressionOpt:=selectExpressionOpt,
operatorTokenKind:=SyntaxKind.LessThanEqualsToken,
operatorKind:=BinaryOperatorKind.LessThanOrEqual,
convertCaseElements:=convertCaseElements,
conditionOpt:=upperBoundConditionOpt,
diagnostics:=diagnostics)
Return New BoundRangeCaseClause(node, lowerBound, upperBound, lowerBoundConditionOpt, upperBoundConditionOpt)
End Function
Private Function BindCaseClauseExpression(
expressionSyntax As ExpressionSyntax,
caseClauseSyntax As CaseClauseSyntax,
selectExpressionOpt As BoundRValuePlaceholder,
operatorTokenKind As SyntaxKind,
operatorKind As BinaryOperatorKind,
convertCaseElements As Boolean,
ByRef conditionOpt As BoundExpression,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim caseExpr As BoundExpression = BindValue(expressionSyntax, diagnostics)
If selectExpressionOpt Is Nothing Then
' In error scenarios, such as a Case statement outside of a
' Select statement, the Select expression may be Nothing.
conditionOpt = Nothing
Return MakeRValue(caseExpr, diagnostics)
End If
If convertCaseElements AndAlso caseExpr.Type.IsIntrinsicOrEnumType() Then
' SPEC: The expression is converted to the type of the Select expression;
' SPEC: if the expression is not implicitly convertible to the type of the Select expression, a compile-time error occurs.
Debug.Assert(selectExpressionOpt.Type IsNot Nothing)
Return ApplyImplicitConversion(expressionSyntax, selectExpressionOpt.Type, caseExpr, diagnostics)
Else
' SPEC: If the Select expression is E, the comparison operator is Op,
' SPEC: and the Case expression is E1, the case is evaluated as E OP E1.
' Bind binary operator "selectExpression OP caseExpr" to generate necessary diagnostics.
conditionOpt = BindBinaryOperator(
node:=caseClauseSyntax,
left:=selectExpressionOpt,
right:=caseExpr,
operatorTokenKind:=operatorTokenKind,
preliminaryOperatorKind:=operatorKind,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
Return Nothing
End If
End Function
#Region "Helper methods for Binding Select case statement"
' This function is identical to the Semantics::OptimizeSelectStatement in native compiler.
' It performs two primary tasks:
' 1) Determines what kind of byte codes will be used for select: Switch Table or If List.
' Ideally we would like to delay these kind of optimizations till rewriting/emit phase.
' However, the computation of the case statement conditional would be redundant if
' we are eventually going to emit Switch table based byte code. Hence we match the
' native compiler behavior and check RecommendSwitchTable() here and store this
' value in the BoundSelectStatement node to be reused in the rewriter.
' 2) If we are going to generate If list based byte code, this function computes the
' conditional expression for case statements and stores it in the BoundCaseStatement nodes.
' Condition for each case statement "Case clause1, clause2, ..., clauseN"
' is computed as "clause1 OrElse clause2 OrElse ... OrElse clauseN" expression.
Private Function OptimizeSelectStatement(
selectExpression As BoundRValuePlaceholder,
caseBlockBuilder As ArrayBuilder(Of BoundCaseBlock),
ByRef generateSwitchTable As Boolean,
diagnostics As BindingDiagnosticBag
) As ImmutableArray(Of BoundCaseBlock)
Debug.Assert(Not selectExpression.HasErrors)
generateSwitchTable = RecommendSwitchTable(selectExpression, caseBlockBuilder, diagnostics)
' CONSIDER: Do we need to compute the case statement conditional expression
' CONSIDER: even for generateSwitchTable case? We might want to do so to
' CONSIDER: maintain consistency of bound nodes coming out of the binder.
' CONSIDER: With the current design, value of BoundCaseStatement.ConditionOpt field
' CONSIDER: is dependent on the value of generateSwitchTable.
If Not generateSwitchTable AndAlso caseBlockBuilder.Any() Then
Dim booleanType = GetSpecialType(SpecialType.System_Boolean, selectExpression.Syntax, diagnostics)
Dim caseClauseBuilder = ArrayBuilder(Of BoundCaseClause).GetInstance()
For index = 0 To caseBlockBuilder.Count - 1
Dim caseBlock = caseBlockBuilder(index)
If caseBlock.Syntax.Kind <> SyntaxKind.CaseElseBlock AndAlso
Not caseBlock.CaseStatement.Syntax.IsMissing Then
Dim caseStatement = caseBlock.CaseStatement
Dim caseStatementSyntax = caseStatement.Syntax
Dim caseStatementCondition As BoundExpression = Nothing
Debug.Assert(caseStatement.CaseClauses.Any())
Dim clausesChanged = False
' Compute conditional expression for case statement
For Each caseClause In caseStatement.CaseClauses
Dim clauseCondition As BoundExpression = Nothing
' Compute conditional expression for case clause, if not already computed.
Dim newCaseClause = ComputeCaseClauseCondition(caseClause, clauseCondition, selectExpression, diagnostics)
caseClauseBuilder.Add(newCaseClause)
clausesChanged = clausesChanged OrElse Not newCaseClause.Equals(caseClause)
Debug.Assert(clauseCondition IsNot Nothing)
If caseStatementCondition Is Nothing Then
caseStatementCondition = clauseCondition
Else
' caseStatementCondition = caseStatementCondition OrElse clauseCondition
caseStatementCondition = BindBinaryOperator(
node:=caseStatementSyntax,
left:=caseStatementCondition,
right:=clauseCondition,
operatorTokenKind:=SyntaxKind.OrElseKeyword,
preliminaryOperatorKind:=BinaryOperatorKind.OrElse,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
Next
Dim newCaseClauses As ImmutableArray(Of BoundCaseClause)
If clausesChanged Then
newCaseClauses = caseClauseBuilder.ToImmutable()
Else
newCaseClauses = caseStatement.CaseClauses
End If
caseClauseBuilder.Clear()
caseStatementCondition = ApplyImplicitConversion(caseStatementCondition.Syntax, booleanType, caseStatementCondition, diagnostics:=diagnostics, isOperandOfConditionalBranch:=True)
caseStatement = caseStatement.Update(newCaseClauses, caseStatementCondition)
caseBlockBuilder(index) = caseBlock.Update(caseStatement, caseBlock.Body)
End If
Next
caseClauseBuilder.Free()
End If
Return caseBlockBuilder.ToImmutableAndFree()
End Function
Private Function ComputeCaseClauseCondition(caseClause As BoundCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Select Case caseClause.Kind
Case BoundKind.RelationalCaseClause
Return ComputeRelationalCaseClauseCondition(DirectCast(caseClause, BoundRelationalCaseClause), conditionOpt, selectExpression, diagnostics)
Case BoundKind.SimpleCaseClause
Return ComputeSimpleCaseClauseCondition(DirectCast(caseClause, BoundSimpleCaseClause), conditionOpt, selectExpression, diagnostics)
Case BoundKind.RangeCaseClause
Return ComputeRangeCaseClauseCondition(DirectCast(caseClause, BoundRangeCaseClause), conditionOpt, selectExpression, diagnostics)
Case Else
Throw ExceptionUtilities.UnexpectedValue(caseClause.Kind)
End Select
End Function
Private Function ComputeRelationalCaseClauseCondition(boundClause As BoundRelationalCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Dim syntax = DirectCast(boundClause.Syntax, RelationalCaseClauseSyntax)
' Exactly one of the operand or condition must be non-null
Debug.Assert(boundClause.ConditionOpt IsNot Nothing Xor boundClause.ValueOpt IsNot Nothing)
conditionOpt = If(boundClause.ConditionOpt, BindBinaryOperator(node:=syntax,
left:=selectExpression,
right:=boundClause.ValueOpt,
operatorTokenKind:=syntax.OperatorToken.Kind,
preliminaryOperatorKind:=boundClause.OperatorKind,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated())
Return boundClause.Update(boundClause.OperatorKind, valueOpt:=Nothing, conditionOpt:=conditionOpt)
End Function
Private Function ComputeSimpleCaseClauseCondition(boundClause As BoundSimpleCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
' Exactly one of the value or condition must be non-null
Debug.Assert(boundClause.ConditionOpt IsNot Nothing Xor boundClause.ValueOpt IsNot Nothing)
conditionOpt = If(boundClause.ConditionOpt, BindBinaryOperator(node:=boundClause.Syntax,
left:=selectExpression,
right:=boundClause.ValueOpt,
operatorTokenKind:=SyntaxKind.EqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.Equals,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated())
Return boundClause.Update(valueOpt:=Nothing, conditionOpt:=conditionOpt)
End Function
Private Function ComputeRangeCaseClauseCondition(boundClause As BoundRangeCaseClause, <Out()> ByRef conditionOpt As BoundExpression, selectExpression As BoundRValuePlaceholder, diagnostics As BindingDiagnosticBag) As BoundCaseClause
Dim syntax = boundClause.Syntax
' Exactly one of the LowerBoundOpt or LowerBoundConditionOpt must be non-null
Debug.Assert(boundClause.LowerBoundOpt IsNot Nothing Xor boundClause.LowerBoundConditionOpt IsNot Nothing)
Dim lowerBoundConditionOpt = boundClause.LowerBoundConditionOpt
If lowerBoundConditionOpt Is Nothing Then
lowerBoundConditionOpt = BindBinaryOperator(
node:=boundClause.Syntax,
left:=selectExpression,
right:=boundClause.LowerBoundOpt,
operatorTokenKind:=SyntaxKind.GreaterThanEqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.GreaterThanOrEqual,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
' Exactly one of the UpperBoundOpt or UpperBoundConditionOpt must be non-null
Debug.Assert(boundClause.UpperBoundOpt IsNot Nothing Xor boundClause.UpperBoundConditionOpt IsNot Nothing)
Dim upperBoundConditionOpt = boundClause.UpperBoundConditionOpt
If upperBoundConditionOpt Is Nothing Then
upperBoundConditionOpt = BindBinaryOperator(
node:=syntax,
left:=selectExpression,
right:=boundClause.UpperBoundOpt,
operatorTokenKind:=SyntaxKind.LessThanEqualsToken,
preliminaryOperatorKind:=BinaryOperatorKind.LessThanOrEqual,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
End If
conditionOpt = BindBinaryOperator(
node:=syntax,
left:=lowerBoundConditionOpt,
right:=upperBoundConditionOpt,
operatorTokenKind:=SyntaxKind.AndAlsoKeyword,
preliminaryOperatorKind:=BinaryOperatorKind.AndAlso,
isOperandOfConditionalBranch:=False,
diagnostics:=diagnostics,
isSelectCase:=True).MakeCompilerGenerated()
Return boundClause.Update(lowerBoundOpt:=Nothing, upperBoundOpt:=Nothing, lowerBoundConditionOpt:=lowerBoundConditionOpt, upperBoundConditionOpt:=upperBoundConditionOpt)
End Function
' Helper method to determine if we must rewrite the select case statement as an IF list or a SWITCH table
Private Function RecommendSwitchTable(selectExpr As BoundRValuePlaceholder, caseBlocks As ArrayBuilder(Of BoundCaseBlock), diagnostics As BindingDiagnosticBag) As Boolean
' We can rewrite select case statement as an IF list or a SWITCH table
' This function determines which method to use.
' The conditions for choosing the SWITCH table are:
' select case expression type must be integral/boolean/string (see TypeSymbolExtensions.IsValidTypeForSwitchTable())
' no "Is <relop>" cases, except for <relop> = BinaryOperatorKind.Equals
' no "<lb> To <ub>" cases for string type
' for integral/boolean type, case values must be (or expand to, as in ranges) integer constants
' for string type, all case values must be string constants and OptionCompareText must be False.
' beneficial over IF lists (as per a threshold on size ratio)
' ranges must have lower bound first
' We also generate warnings for Invalid range clauses in this function.
' Ideally we would like to generate them in BindRangeCaseClause.
' However, Dev10 doesn't do this check individually for each CaseClause.
' It is performed only if bounds for all clauses in the Select are integer constants and
' all clauses are either range clauses or equality clause.
' Doing this differently will produce warnings in more scenarios - breaking change.
If Not caseBlocks.Any() OrElse Not selectExpr.Type.IsValidTypeForSwitchTable() Then
Return False
End If
Dim isSelectExprStringType = selectExpr.Type.IsStringType
If isSelectExprStringType AndAlso OptionCompareText Then
Return False
End If
Dim recommendSwitch = True
For Each caseBlock In caseBlocks
For Each caseClause In caseBlock.CaseStatement.CaseClauses
Select Case caseClause.Kind
Case BoundKind.RelationalCaseClause
Dim relationalClause = DirectCast(caseClause, BoundRelationalCaseClause)
' Exactly one of the operand or condition must be non-null
Debug.Assert(relationalClause.ValueOpt IsNot Nothing Xor relationalClause.ConditionOpt IsNot Nothing)
Dim operand = relationalClause.ValueOpt
If operand Is Nothing OrElse
relationalClause.OperatorKind <> BinaryOperatorKind.Equals OrElse
operand.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(operand.ConstantValueOpt) Then
Return False
End If
Case BoundKind.RangeCaseClause
' TODO: RecommendSwitchTable for Range clause.
' TODO: If we decide to implement it we will need to
' TODO: add heuristic to determine when the range is
' TODO: big enough to prefer IF lists over SWITCH table.
' TODO: We will also need to add logic in the emitter
' TODO: to iterate through ConstantValues in a range.
' For now we use IF lists if we encounter BoundRangeCaseClause
Dim rangeCaseClause = DirectCast(caseClause, BoundRangeCaseClause)
' Exactly one of the LowerBoundOpt or LowerBoundConditionOpt must be non-null
Debug.Assert(rangeCaseClause.LowerBoundOpt IsNot Nothing Xor rangeCaseClause.LowerBoundConditionOpt IsNot Nothing)
' Exactly one of the UpperBoundOpt or UpperBoundConditionOpt must be non-null
Debug.Assert(rangeCaseClause.UpperBoundOpt IsNot Nothing Xor rangeCaseClause.UpperBoundConditionOpt IsNot Nothing)
Dim lowerBound = rangeCaseClause.LowerBoundOpt
Dim upperBound = rangeCaseClause.UpperBoundOpt
If lowerBound Is Nothing OrElse
upperBound Is Nothing OrElse
lowerBound.ConstantValueOpt Is Nothing OrElse
upperBound.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(lowerBound.ConstantValueOpt) OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(upperBound.ConstantValueOpt) Then
Return False
End If
recommendSwitch = False
Case Else
Dim simpleCaseClause = DirectCast(caseClause, BoundSimpleCaseClause)
' Exactly one of the value or condition must be non-null
Debug.Assert(simpleCaseClause.ValueOpt IsNot Nothing Xor simpleCaseClause.ConditionOpt IsNot Nothing)
Dim value = simpleCaseClause.ValueOpt
If value Is Nothing OrElse
value.ConstantValueOpt Is Nothing OrElse
Not SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(value.ConstantValueOpt) Then
Return False
End If
End Select
Next
Next
' TODO: beneficial over IF lists (as per a threshold on size ratio)
Return Not ReportInvalidSelectCaseRange(caseBlocks, diagnostics) AndAlso recommendSwitch
End Function
' Function reports WRN_SelectCaseInvalidRange for any invalid select case range.
' Returns True if an invalid range was found, False otherwise.
Private Function ReportInvalidSelectCaseRange(caseBlocks As ArrayBuilder(Of BoundCaseBlock), diagnostics As BindingDiagnosticBag) As Boolean
For Each caseBlock In caseBlocks
For Each caseClause In caseBlock.CaseStatement.CaseClauses
Select Case caseClause.Kind
Case BoundKind.RangeCaseClause
Dim rangeCaseClause = DirectCast(caseClause, BoundRangeCaseClause)
Dim lowerBound = rangeCaseClause.LowerBoundOpt
Dim upperBound = rangeCaseClause.UpperBoundOpt
Debug.Assert(lowerBound IsNot Nothing)
Debug.Assert(lowerBound.ConstantValueOpt IsNot Nothing)
Debug.Assert(upperBound IsNot Nothing)
Debug.Assert(upperBound.ConstantValueOpt IsNot Nothing)
Debug.Assert(rangeCaseClause.LowerBoundConditionOpt Is Nothing)
Debug.Assert(rangeCaseClause.UpperBoundConditionOpt Is Nothing)
If IsInvalidSelectCaseRange(lowerBound.ConstantValueOpt, upperBound.ConstantValueOpt) Then
ReportDiagnostic(diagnostics, rangeCaseClause.Syntax, ERRID.WRN_SelectCaseInvalidRange)
Return True
End If
End Select
Next
Next
Return False
End Function
Private Shared Function IsInvalidSelectCaseRange(lbConstantValue As ConstantValue, ubConstantValue As ConstantValue) As Boolean
Debug.Assert(lbConstantValue IsNot Nothing)
Debug.Assert(ubConstantValue IsNot Nothing)
Debug.Assert(lbConstantValue.SpecialType = ubConstantValue.SpecialType)
Select Case lbConstantValue.SpecialType
Case SpecialType.System_Boolean,
SpecialType.System_Byte,
SpecialType.System_UInt16,
SpecialType.System_UInt32,
SpecialType.System_UInt64
Return lbConstantValue.UInt64Value > ubConstantValue.UInt64Value
Case SpecialType.System_SByte,
SpecialType.System_Int16,
SpecialType.System_Int32,
SpecialType.System_Int64,
SpecialType.System_Char
Return lbConstantValue.Int64Value > ubConstantValue.Int64Value
Case SpecialType.System_Single,
SpecialType.System_Double
Return lbConstantValue.DoubleValue > ubConstantValue.DoubleValue
Case SpecialType.System_Decimal
Return lbConstantValue.DecimalValue > ubConstantValue.DecimalValue
Case Else
Return False
End Select
End Function
#End Region
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class GeneratorDriverTests
: CSharpTestBase
{
[Fact]
public void Running_With_No_Changes_Is_NoOp()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Empty(diagnostics);
Assert.Single(outputCompilation.SyntaxTrees);
Assert.Equal(compilation, outputCompilation);
}
[Fact]
public void Generator_Is_Initialized_Before_Running()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
}
[Fact]
public void Generator_Is_Not_Initialized_If_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
Assert.Equal(0, initCount);
Assert.Equal(0, executeCount);
}
[Fact]
public void Generator_Is_Only_Initialized_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
Assert.Equal(1, initCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Single_File_Is_Added()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation);
var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single();
Assert.True(generatedClass.Locations.Single().IsInSource);
}
[Fact]
public void Analyzer_Is_Run()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
var analyzer = new Analyzer_Is_Run_Analyzer();
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(0, analyzer.GeneratedClassCount);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.GeneratedClassCount);
}
private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer
{
public int GeneratedClassCount;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle, SymbolKind.NamedType);
}
private void Handle(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "GeneratedClass":
Interlocked.Increment(ref GeneratedClassCount);
break;
case "C":
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _);
Assert.Equal(2, outputCompilation1.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation2.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation3.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation1);
Assert.NotEqual(compilation, outputCompilation2);
Assert.NotEqual(compilation, outputCompilation3);
}
[Fact]
public void User_Source_Can_Depend_On_Generated_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
}
[Fact]
public void Error_During_Initialization_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_Generator_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Single(outputCompilation.SyntaxTrees);
}
[Fact]
public void Error_During_Generation_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Does_Not_Affect_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_With_Dependent_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Has_Exception_In_Description()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
// Since translated description strings can have punctuation that differs based on locale, simply ensure the
// exception message is contains in the diagnostic description.
Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString());
}
[Fact]
public void Generator_Can_Report_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
Diagnostic("TG001").WithLocation(1, 1)
);
}
[Fact]
public void Generator_HintName_MustBe_Unique()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) =>
{
sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
// the assert should swallow the exception, so we'll actually successfully generate
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
// also throws for <name> vs <name>.cs
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")]
public void Generator_HintName_MustBe_Unique_Across_Outputs()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview);
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) =>
{
spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
// throws immediately, because we're within the same output node
Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
// throws for .cs too
Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
});
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) =>
{
// will not throw at this point, because we have no way of knowing what the other outputs added
// we *will* throw later in the driver when we combine them however (this is a change for V2, but not visible from V1)
spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
});
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
Diagnostic("CS8785").WithArguments("PipelineCallbackGenerator", "ArgumentException", "The hintName 'test.cs' of the added source file must be unique within a generator. (Parameter 'hintName')").WithLocation(1, 1)
);
Assert.Equal(1, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void Generator_HintName_Is_Appended_With_GeneratorName()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(3, outputCompilation.SyntaxTrees.Count());
var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray();
Assert.Equal(new[] {
Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"),
Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs")
}, filePaths);
}
[Fact]
public void RunResults_Are_Empty_Before_Generation()
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular);
var results = driver.GetRunResult();
Assert.Empty(results.GeneratedTrees);
Assert.Empty(results.Diagnostics);
Assert.Empty(results.Results);
}
[Fact]
public void RunResults_Are_Available_After_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.GeneratedTrees);
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results.Single();
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Single(result.GeneratedSources);
Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree);
}
[Fact]
public void RunResults_Combine_SyntaxTrees()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); });
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void RunResults_Combine_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(2, results.Results.Length);
Assert.Equal(3, results.Diagnostics.Length);
Assert.Empty(results.GeneratedTrees);
var result1 = results.Results[0];
var result2 = results.Results[1];
Assert.Null(result1.Exception);
Assert.Equal(2, result1.Diagnostics.Length);
Assert.Empty(result1.GeneratedSources);
Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]);
Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]);
Assert.Null(result2.Exception);
Assert.Single(result2.Diagnostics);
Assert.Empty(result2.GeneratedSources);
Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]);
}
[Fact]
public void FullGeneration_Diagnostics_AreSame_As_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics);
var results = driver.GetRunResult();
Assert.Equal(3, results.Diagnostics.Length);
Assert.Equal(3, fullDiagnostics.Length);
AssertEx.Equal(results.Diagnostics, fullDiagnostics);
}
[Fact]
public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { cts.Cancel(); }
);
// test generator cancels the token. Check that the call to this generator doesn't make it look like it errored.
var testGenerator2 = new CallbackGenerator2(
onInit: (i) => { },
onExecute: (e) =>
{
e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8));
e.CancellationToken.ThrowIfCancellationRequested();
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions);
var oldDriver = driver;
Assert.Throws<OperationCanceledException>(() =>
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token)
);
Assert.Same(oldDriver, driver);
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")]
public void Adding_A_Source_Text_Without_Encoding_Fails_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics);
Assert.Single(outputDiagnostics);
outputDiagnostics.Verify(
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1)
);
}
[Fact]
public void ParseOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
ParseOptions? passedOptions = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { passedOptions = e.ParseOptions; }
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Same(parseOptions, passedOptions);
}
[Fact]
public void AdditionalFiles_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def"));
ImmutableArray<AdditionalText> passedIn = default;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AdditionalFiles
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Equal(2, passedIn.Length);
Assert.Equal<AdditionalText>(texts, passedIn);
}
[Fact]
public void AnalyzerConfigOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def")));
AnalyzerConfigOptionsProvider? passedIn = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AnalyzerConfigOptions
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.NotNull(passedIn);
Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1));
Assert.Equal("abc", item1);
Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2));
Assert.Equal("def", item2);
}
[Fact]
public void Generator_Can_Provide_Source_In_PostInit()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void PostInit_Source_Is_Available_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Is_Only_Called_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int postInitCount = 0;
int executeCount = 0;
void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
postInitCount++;
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(1, postInitCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Error_During_PostInit_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
throw new InvalidOperationException("post init error");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_PostInit_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void init(GeneratorInitializationContext context)
{
context.RegisterForPostInitialization(postInit);
throw new InvalidOperationException("init error");
}
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
Assert.True(false, "Should not execute");
}
var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Available_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results[0];
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Equal(2, result.GeneratedSources.Length);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Combined_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void SyntaxTrees_Are_Lazy()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
var tree = Assert.Single(results.GeneratedTrees);
Assert.False(tree.TryGetRoot(out _));
var rootFromGetRoot = tree.GetRoot();
Assert.NotNull(rootFromGetRoot);
Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot));
Assert.Same(rootFromGetRoot, rootFromTryGetRoot);
}
[Fact]
public void Diagnostics_Respect_Suppression()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2));
c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3));
});
var options = ((CSharpCompilationOptions)compilation.Options);
// generator driver diagnostics are reported separately from the compilation
verifyDiagnosticsWithOptions(options,
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be individually suppressed
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress),
Diagnostic("GEN001").WithLocation(1, 1));
// warning level is respected
verifyDiagnosticsWithOptions(options.WithWarningLevel(0));
verifyDiagnosticsWithOptions(options.WithWarningLevel(2),
Diagnostic("GEN001").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithWarningLevel(3),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be upgraded to errors
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true));
void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected)
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
var updatedCompilation = compilation.WithOptions(options);
driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void Diagnostics_Respect_Pragma_Suppression()
{
var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2);
// reported diagnostics can have a location in source
verifyDiagnosticsWithSource("//comment",
new[] { (gen001, TextSpan.FromBounds(2, 5)) },
Diagnostic("GEN001", "com").WithLocation(1, 3));
// diagnostics are suppressed via #pragma
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, TextSpan.FromBounds(27, 30)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// but not when they don't have a source location
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, new TextSpan(0, 0)) },
Diagnostic("GEN001").WithLocation(1, 1));
// can be suppressed explicitly
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment",
new[] { (gen001, TextSpan.FromBounds(34, 37)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// suppress + restore
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment
#pragma warning restore GEN001
//another",
new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3),
Diagnostic("GEN001", "ano").WithLocation(4, 3));
void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected)
{
var parseOptions = TestOptions.Regular;
source = source.Replace(Environment.NewLine, "\r\n");
Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
foreach ((var d, var l) in reportDiagnostics)
{
if (l.IsEmpty)
{
c.ReportDiagnostic(d);
}
else
{
c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l)));
}
}
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void GeneratorDriver_Prefers_Incremental_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
int incrementalInitCount = 0;
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0;
var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran individual incremental and source generators
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
Assert.Equal(1, incrementalInitCount);
// ran the combined generator only as an IIncrementalGenerator
Assert.Equal(0, dualInitCount);
Assert.Equal(0, dualExecuteCount);
Assert.Equal(1, dualIncrementalInitCount);
}
[Fact]
public void GeneratorDriver_Initializes_Incremental_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int incrementalInitCount = 0;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran the incremental generator
Assert.Equal(1, incrementalInitCount);
}
[Fact]
public void Incremental_Generators_Exception_During_Initialization()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e)));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Equal(2, runResults.Results.Length);
Assert.Single(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { }));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Empty(diagnostics);
}
[Fact]
public void IncrementalGenerator_Can_Add_PostInit_Source()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"))));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.Empty(diagnostics);
}
[Fact]
public void User_WrappedFunc_Throw_Exceptions()
{
Func<int, CancellationToken, int> func = (input, _) => input;
Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception");
Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; };
Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException();
var userFunc = func.WrapUserFunction();
var userThrowsFunc = throwsFunc.WrapUserFunction();
var userTimeoutFunc = timeoutFunc.WrapUserFunction();
var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction();
// user functions return same values when wrapped
var result = userFunc(10, CancellationToken.None);
var userResult = userFunc(10, CancellationToken.None);
Assert.Equal(10, result);
Assert.Equal(result, userResult);
// exceptions thrown in user code are wrapped
Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None));
try
{
userThrowsFunc(20, CancellationToken.None);
}
catch (UserFunctionException e)
{
Assert.IsType<InvalidOperationException>(e.InnerException);
}
// cancellation is not wrapped, and is bubbled up
Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true)));
Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true)));
// unless it wasn't *our* cancellation token, in which case it still gets wrapped
Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None));
}
[Fact]
public void IncrementalGenerator_Doesnt_Run_For_Same_Input()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath);
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// run the same compilation through again, and confirm the output wasn't called
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Runs_Only_For_Changed_Inputs()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var text1 = new InMemoryAdditionalText("Text1", "content1");
var text2 = new InMemoryAdditionalText("Text2", "content2");
List<Compilation> compilationsCalledFor = new List<Compilation>();
List<AdditionalText> textsCalledFor = new List<AdditionalText>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text1, textsCalledFor[0]);
// clear the results, add an additional text, but keep the compilation the same
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2));
driver = driver.RunGenerators(compilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text2, textsCalledFor[0]);
// now edit the compilation
compilationsCalledFor.Clear();
textsCalledFor.Clear();
var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(newCompilation, compilationsCalledFor[0]);
Assert.Equal(0, textsCalledFor.Count);
// re run without changing anything
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.RunGenerators(newCompilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(0, textsCalledFor.Count);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
compilationsCalledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// now edit the compilation, run the generator, and confirm that the output was not called again this time
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") };
List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect())
// comparer that ignores the LHS (additional texts)
.WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
calledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation + additional texts
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
Assert.Equal(compilation, calledFor[0].Item1);
Assert.Equal(texts[0], calledFor[0].Item2.Single());
// edit the additional texts, and verify that the output was *not* called again on the next run
driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray());
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
// now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(2, calledFor.Count);
Assert.Equal(newCompilation, calledFor[1].Item1);
Assert.Empty(calledFor[1].Item2);
}
[Fact]
public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var source = ctx.CompilationProvider;
var source2 = ctx.CompilationProvider.Combine(source);
var source3 = ctx.CompilationProvider.Combine(source2);
var source4 = ctx.CompilationProvider.Combine(source3);
var source5 = ctx.CompilationProvider.Combine(source4);
ctx.RegisterSourceOutput(source5, (spc, c) =>
{
compilationsCalledFor.Add(c.Item1);
});
}));
// run the generator and check that we didn't multiple register the generate source node through the combine
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_PostInit_Source_Is_Cached()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"));
ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(2, classes.Count);
Assert.Equal("C", classes[0].Identifier.ValueText);
Assert.Equal("D", classes[1].Identifier.ValueText);
// clear classes, re-run
classes.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(classes);
// modify the original tree, see that the post init is still cached
var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions));
classes.Clear();
driver = driver.RunGenerators(c2);
Assert.Single(classes);
Assert.Equal("E", classes[0].Identifier.ValueText);
}
[Fact]
public void Incremental_Generators_Can_Be_Cancelled()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
bool generatorCancelled = false;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; });
var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; });
ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token));
Assert.True(generatorCancelled);
}
[Fact]
public void ParseOptions_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); });
}));
// run the generator once, and check it was passed the parse options
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(parseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// now update the parse options
parseOptionsCalledFor.Clear();
var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
driver = driver.WithUpdatedParseOptions(newParseOptions);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(newParseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!));
}
[Fact]
public void AnalyzerConfig_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string? analyzerOptionsValue = string.Empty;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue));
}));
var builder = ImmutableDictionary<string, string>.Empty.ToBuilder();
builder.Add("test", "value1");
var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
// run the generator once, and check it was passed the configs
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider);
driver = driver.RunGenerators(compilation);
Assert.Equal("value1", analyzerOptionsValue);
// clear the results, and re-run
analyzerOptionsValue = null;
driver = driver.RunGenerators(compilation);
Assert.Null(analyzerOptionsValue);
// now update the config
analyzerOptionsValue = null;
builder.Clear();
builder.Add("test", "value2");
var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal("value2", analyzerOptionsValue);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!));
}
[Fact]
public void AdditionalText_Can_Be_Replaced()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", "");
InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", "");
InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", "");
List<string?> additionalTextPaths = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 });
driver = driver.RunGenerators(compilation);
Assert.Equal(3, additionalTextPaths.Count);
Assert.Equal("path1.txt", additionalTextPaths[0]);
Assert.Equal("path2.txt", additionalTextPaths[1]);
Assert.Equal("path3.txt", additionalTextPaths[2]);
// re-run and check nothing else got added
additionalTextPaths.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", ""));
// run, and check that only the replaced file was invoked
driver = driver.RunGenerators(compilation);
Assert.Single(additionalTextPaths);
Assert.Equal("path4.txt", additionalTextPaths[0]);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!));
}
[Fact]
public void Replaced_Input_Is_Treated_As_Modified()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc");
List<string?> additionalTextPaths = new List<string?>();
List<string?> additionalTextsContents = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var texts = ctx.AdditionalTextsProvider;
var paths = texts.Select((t, _) => t?.Path);
var contents = texts.Select((t, _) => t?.GetText()?.ToString());
ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); });
ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText });
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path.txt", additionalTextPaths[0]);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("abc", additionalTextsContents[0]);
// re-run and check nothing else got added
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal(1, additionalTextsContents.Count);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var secondText = new InMemoryAdditionalText("path.txt", "def");
driver = driver.ReplaceAdditionalText(additionalText, secondText);
// run, and check that only the contents got re-run
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("def", additionalTextsContents[0]);
// now replace the text with a different path, but the same text
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var thirdText = new InMemoryAdditionalText("path2.txt", "def");
driver = driver.ReplaceAdditionalText(secondText, thirdText);
// run, and check that only the paths got re-run
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path2.txt", additionalTextPaths[0]);
Assert.Empty(additionalTextsContents);
}
[Theory]
[CombinatorialData]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput)
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", ""));
ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", ""));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var result = driver.GetRunResult();
Assert.Single(result.Results);
Assert.Empty(result.Results[0].Diagnostics);
// verify the expected outputs were generated
// NOTE: adding new output types will cause this test to fail. Update above as needed.
foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind)))
{
if (kind == IncrementalGeneratorOutputKind.None)
continue;
if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind))
{
Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind);
}
else
{
Assert.Contains(result.Results[0].GeneratedSources, isTextForKind);
}
bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs";
}
}
[Fact]
public void Metadata_References_Provider()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
var metadataRefs = new[] {
MetadataReference.CreateFromAssemblyInternal(this.GetType().Assembly),
MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly)
};
Compilation compilation = CreateEmptyCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions, references: metadataRefs);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<string?> referenceList = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.MetadataReferencesProvider, (spc, r) => { referenceList.Add(r.Display); });
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(referenceList[0], metadataRefs[0].Display);
Assert.Equal(referenceList[1], metadataRefs[1].Display);
// re-run and check we didn't see anything new
referenceList.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(referenceList);
// Modify the reference
var modifiedRef = metadataRefs[0].WithAliases(new[] { "Alias " });
metadataRefs[0] = modifiedRef;
compilation = compilation.WithReferences(metadataRefs);
driver = driver.RunGenerators(compilation);
Assert.Single(referenceList, modifiedRef.Display);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class GeneratorDriverTests
: CSharpTestBase
{
[Fact]
public void Running_With_No_Changes_Is_NoOp()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Empty(diagnostics);
Assert.Single(outputCompilation.SyntaxTrees);
Assert.Equal(compilation, outputCompilation);
}
[Fact]
public void Generator_Is_Initialized_Before_Running()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
}
[Fact]
public void Generator_Is_Not_Initialized_If_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
Assert.Equal(0, initCount);
Assert.Equal(0, executeCount);
}
[Fact]
public void Generator_Is_Only_Initialized_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
Assert.Equal(1, initCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Single_File_Is_Added()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation);
var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single();
Assert.True(generatedClass.Locations.Single().IsInSource);
}
[Fact]
public void Analyzer_Is_Run()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
var analyzer = new Analyzer_Is_Run_Analyzer();
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(0, analyzer.GeneratedClassCount);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.GeneratedClassCount);
}
private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer
{
public int GeneratedClassCount;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle, SymbolKind.NamedType);
}
private void Handle(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "GeneratedClass":
Interlocked.Increment(ref GeneratedClassCount);
break;
case "C":
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _);
Assert.Equal(2, outputCompilation1.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation2.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation3.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation1);
Assert.NotEqual(compilation, outputCompilation2);
Assert.NotEqual(compilation, outputCompilation3);
}
[Fact]
public void User_Source_Can_Depend_On_Generated_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
}
[Fact]
public void Error_During_Initialization_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_Generator_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Single(outputCompilation.SyntaxTrees);
}
[Fact]
public void Error_During_Generation_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Does_Not_Affect_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_With_Dependent_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Has_Exception_In_Description()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
// Since translated description strings can have punctuation that differs based on locale, simply ensure the
// exception message is contains in the diagnostic description.
Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString());
}
[Fact]
public void Generator_Can_Report_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
Diagnostic("TG001").WithLocation(1, 1)
);
}
[Fact]
public void Generator_HintName_MustBe_Unique()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) =>
{
sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
// the assert should swallow the exception, so we'll actually successfully generate
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
// also throws for <name> vs <name>.cs
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")]
public void Generator_HintName_MustBe_Unique_Across_Outputs()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview);
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) =>
{
spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
// throws immediately, because we're within the same output node
Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
// throws for .cs too
Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
});
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) =>
{
// will not throw at this point, because we have no way of knowing what the other outputs added
// we *will* throw later in the driver when we combine them however (this is a change for V2, but not visible from V1)
spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
});
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
Diagnostic("CS8785").WithArguments("PipelineCallbackGenerator", "ArgumentException", "The hintName 'test.cs' of the added source file must be unique within a generator. (Parameter 'hintName')").WithLocation(1, 1)
);
Assert.Equal(1, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void Generator_HintName_Is_Appended_With_GeneratorName()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(3, outputCompilation.SyntaxTrees.Count());
var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray();
Assert.Equal(new[] {
Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"),
Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs")
}, filePaths);
}
[Fact]
public void RunResults_Are_Empty_Before_Generation()
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular);
var results = driver.GetRunResult();
Assert.Empty(results.GeneratedTrees);
Assert.Empty(results.Diagnostics);
Assert.Empty(results.Results);
}
[Fact]
public void RunResults_Are_Available_After_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.GeneratedTrees);
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results.Single();
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Single(result.GeneratedSources);
Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree);
}
[Fact]
public void RunResults_Combine_SyntaxTrees()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); });
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void RunResults_Combine_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(2, results.Results.Length);
Assert.Equal(3, results.Diagnostics.Length);
Assert.Empty(results.GeneratedTrees);
var result1 = results.Results[0];
var result2 = results.Results[1];
Assert.Null(result1.Exception);
Assert.Equal(2, result1.Diagnostics.Length);
Assert.Empty(result1.GeneratedSources);
Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]);
Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]);
Assert.Null(result2.Exception);
Assert.Single(result2.Diagnostics);
Assert.Empty(result2.GeneratedSources);
Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]);
}
[Fact]
public void FullGeneration_Diagnostics_AreSame_As_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics);
var results = driver.GetRunResult();
Assert.Equal(3, results.Diagnostics.Length);
Assert.Equal(3, fullDiagnostics.Length);
AssertEx.Equal(results.Diagnostics, fullDiagnostics);
}
[Fact]
public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { cts.Cancel(); }
);
// test generator cancels the token. Check that the call to this generator doesn't make it look like it errored.
var testGenerator2 = new CallbackGenerator2(
onInit: (i) => { },
onExecute: (e) =>
{
e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8));
e.CancellationToken.ThrowIfCancellationRequested();
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions);
var oldDriver = driver;
Assert.Throws<OperationCanceledException>(() =>
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token)
);
Assert.Same(oldDriver, driver);
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")]
public void Adding_A_Source_Text_Without_Encoding_Fails_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics);
Assert.Single(outputDiagnostics);
outputDiagnostics.Verify(
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1)
);
}
[Fact]
public void ParseOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
ParseOptions? passedOptions = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { passedOptions = e.ParseOptions; }
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Same(parseOptions, passedOptions);
}
[Fact]
public void AdditionalFiles_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def"));
ImmutableArray<AdditionalText> passedIn = default;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AdditionalFiles
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Equal(2, passedIn.Length);
Assert.Equal<AdditionalText>(texts, passedIn);
}
[Fact]
public void AnalyzerConfigOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def")));
AnalyzerConfigOptionsProvider? passedIn = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AnalyzerConfigOptions
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.NotNull(passedIn);
Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1));
Assert.Equal("abc", item1);
Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2));
Assert.Equal("def", item2);
}
[Fact]
public void Generator_Can_Provide_Source_In_PostInit()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void PostInit_Source_Is_Available_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Is_Only_Called_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int postInitCount = 0;
int executeCount = 0;
void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
postInitCount++;
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(1, postInitCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Error_During_PostInit_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
throw new InvalidOperationException("post init error");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_PostInit_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void init(GeneratorInitializationContext context)
{
context.RegisterForPostInitialization(postInit);
throw new InvalidOperationException("init error");
}
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
Assert.True(false, "Should not execute");
}
var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Available_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results[0];
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Equal(2, result.GeneratedSources.Length);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Combined_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void SyntaxTrees_Are_Lazy()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
var tree = Assert.Single(results.GeneratedTrees);
Assert.False(tree.TryGetRoot(out _));
var rootFromGetRoot = tree.GetRoot();
Assert.NotNull(rootFromGetRoot);
Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot));
Assert.Same(rootFromGetRoot, rootFromTryGetRoot);
}
[Fact]
public void Diagnostics_Respect_Suppression()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2));
c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3));
});
var options = ((CSharpCompilationOptions)compilation.Options);
// generator driver diagnostics are reported separately from the compilation
verifyDiagnosticsWithOptions(options,
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be individually suppressed
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress),
Diagnostic("GEN001").WithLocation(1, 1));
// warning level is respected
verifyDiagnosticsWithOptions(options.WithWarningLevel(0));
verifyDiagnosticsWithOptions(options.WithWarningLevel(2),
Diagnostic("GEN001").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithWarningLevel(3),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be upgraded to errors
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true));
void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected)
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
var updatedCompilation = compilation.WithOptions(options);
driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void Diagnostics_Respect_Pragma_Suppression()
{
var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2);
// reported diagnostics can have a location in source
verifyDiagnosticsWithSource("//comment",
new[] { (gen001, TextSpan.FromBounds(2, 5)) },
Diagnostic("GEN001", "com").WithLocation(1, 3));
// diagnostics are suppressed via #pragma
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, TextSpan.FromBounds(27, 30)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// but not when they don't have a source location
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, new TextSpan(0, 0)) },
Diagnostic("GEN001").WithLocation(1, 1));
// can be suppressed explicitly
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment",
new[] { (gen001, TextSpan.FromBounds(34, 37)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// suppress + restore
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment
#pragma warning restore GEN001
//another",
new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3),
Diagnostic("GEN001", "ano").WithLocation(4, 3));
void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected)
{
var parseOptions = TestOptions.Regular;
source = source.Replace(Environment.NewLine, "\r\n");
Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
foreach ((var d, var l) in reportDiagnostics)
{
if (l.IsEmpty)
{
c.ReportDiagnostic(d);
}
else
{
c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l)));
}
}
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void GeneratorDriver_Prefers_Incremental_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
int incrementalInitCount = 0;
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0;
var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran individual incremental and source generators
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
Assert.Equal(1, incrementalInitCount);
// ran the combined generator only as an IIncrementalGenerator
Assert.Equal(0, dualInitCount);
Assert.Equal(0, dualExecuteCount);
Assert.Equal(1, dualIncrementalInitCount);
}
[Fact]
public void GeneratorDriver_Initializes_Incremental_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int incrementalInitCount = 0;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran the incremental generator
Assert.Equal(1, incrementalInitCount);
}
[Fact]
public void Incremental_Generators_Exception_During_Initialization()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e)));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Equal(2, runResults.Results.Length);
Assert.Single(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { }));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Empty(diagnostics);
}
[Fact]
public void IncrementalGenerator_Can_Add_PostInit_Source()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"))));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.Empty(diagnostics);
}
[Fact]
public void User_WrappedFunc_Throw_Exceptions()
{
Func<int, CancellationToken, int> func = (input, _) => input;
Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception");
Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; };
Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException();
var userFunc = func.WrapUserFunction();
var userThrowsFunc = throwsFunc.WrapUserFunction();
var userTimeoutFunc = timeoutFunc.WrapUserFunction();
var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction();
// user functions return same values when wrapped
var result = userFunc(10, CancellationToken.None);
var userResult = userFunc(10, CancellationToken.None);
Assert.Equal(10, result);
Assert.Equal(result, userResult);
// exceptions thrown in user code are wrapped
Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None));
try
{
userThrowsFunc(20, CancellationToken.None);
}
catch (UserFunctionException e)
{
Assert.IsType<InvalidOperationException>(e.InnerException);
}
// cancellation is not wrapped, and is bubbled up
Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true)));
Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true)));
// unless it wasn't *our* cancellation token, in which case it still gets wrapped
Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None));
}
[Fact]
public void IncrementalGenerator_Doesnt_Run_For_Same_Input()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath);
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// run the same compilation through again, and confirm the output wasn't called
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Runs_Only_For_Changed_Inputs()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var text1 = new InMemoryAdditionalText("Text1", "content1");
var text2 = new InMemoryAdditionalText("Text2", "content2");
List<Compilation> compilationsCalledFor = new List<Compilation>();
List<AdditionalText> textsCalledFor = new List<AdditionalText>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text1, textsCalledFor[0]);
// clear the results, add an additional text, but keep the compilation the same
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2));
driver = driver.RunGenerators(compilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text2, textsCalledFor[0]);
// now edit the compilation
compilationsCalledFor.Clear();
textsCalledFor.Clear();
var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(newCompilation, compilationsCalledFor[0]);
Assert.Equal(0, textsCalledFor.Count);
// re run without changing anything
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.RunGenerators(newCompilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(0, textsCalledFor.Count);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
compilationsCalledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// now edit the compilation, run the generator, and confirm that the output was not called again this time
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") };
List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect())
// comparer that ignores the LHS (additional texts)
.WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
calledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation + additional texts
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
Assert.Equal(compilation, calledFor[0].Item1);
Assert.Equal(texts[0], calledFor[0].Item2.Single());
// edit the additional texts, and verify that the output was *not* called again on the next run
driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray());
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
// now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(2, calledFor.Count);
Assert.Equal(newCompilation, calledFor[1].Item1);
Assert.Empty(calledFor[1].Item2);
}
[Fact]
public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var source = ctx.CompilationProvider;
var source2 = ctx.CompilationProvider.Combine(source);
var source3 = ctx.CompilationProvider.Combine(source2);
var source4 = ctx.CompilationProvider.Combine(source3);
var source5 = ctx.CompilationProvider.Combine(source4);
ctx.RegisterSourceOutput(source5, (spc, c) =>
{
compilationsCalledFor.Add(c.Item1);
});
}));
// run the generator and check that we didn't multiple register the generate source node through the combine
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_PostInit_Source_Is_Cached()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"));
ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(2, classes.Count);
Assert.Equal("C", classes[0].Identifier.ValueText);
Assert.Equal("D", classes[1].Identifier.ValueText);
// clear classes, re-run
classes.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(classes);
// modify the original tree, see that the post init is still cached
var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions));
classes.Clear();
driver = driver.RunGenerators(c2);
Assert.Single(classes);
Assert.Equal("E", classes[0].Identifier.ValueText);
}
[Fact]
public void Incremental_Generators_Can_Be_Cancelled()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
bool generatorCancelled = false;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; });
var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; });
ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token));
Assert.True(generatorCancelled);
}
[Fact]
public void ParseOptions_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); });
}));
// run the generator once, and check it was passed the parse options
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(parseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// now update the parse options
parseOptionsCalledFor.Clear();
var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
driver = driver.WithUpdatedParseOptions(newParseOptions);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(newParseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!));
}
[Fact]
public void AnalyzerConfig_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string? analyzerOptionsValue = string.Empty;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue));
}));
var builder = ImmutableDictionary<string, string>.Empty.ToBuilder();
builder.Add("test", "value1");
var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
// run the generator once, and check it was passed the configs
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider);
driver = driver.RunGenerators(compilation);
Assert.Equal("value1", analyzerOptionsValue);
// clear the results, and re-run
analyzerOptionsValue = null;
driver = driver.RunGenerators(compilation);
Assert.Null(analyzerOptionsValue);
// now update the config
analyzerOptionsValue = null;
builder.Clear();
builder.Add("test", "value2");
var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal("value2", analyzerOptionsValue);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!));
}
[Fact]
public void AdditionalText_Can_Be_Replaced()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", "");
InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", "");
InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", "");
List<string?> additionalTextPaths = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 });
driver = driver.RunGenerators(compilation);
Assert.Equal(3, additionalTextPaths.Count);
Assert.Equal("path1.txt", additionalTextPaths[0]);
Assert.Equal("path2.txt", additionalTextPaths[1]);
Assert.Equal("path3.txt", additionalTextPaths[2]);
// re-run and check nothing else got added
additionalTextPaths.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", ""));
// run, and check that only the replaced file was invoked
driver = driver.RunGenerators(compilation);
Assert.Single(additionalTextPaths);
Assert.Equal("path4.txt", additionalTextPaths[0]);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!));
}
[Fact]
public void Replaced_Input_Is_Treated_As_Modified()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc");
List<string?> additionalTextPaths = new List<string?>();
List<string?> additionalTextsContents = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var texts = ctx.AdditionalTextsProvider;
var paths = texts.Select((t, _) => t?.Path);
var contents = texts.Select((t, _) => t?.GetText()?.ToString());
ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); });
ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText });
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path.txt", additionalTextPaths[0]);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("abc", additionalTextsContents[0]);
// re-run and check nothing else got added
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal(1, additionalTextsContents.Count);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var secondText = new InMemoryAdditionalText("path.txt", "def");
driver = driver.ReplaceAdditionalText(additionalText, secondText);
// run, and check that only the contents got re-run
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("def", additionalTextsContents[0]);
// now replace the text with a different path, but the same text
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var thirdText = new InMemoryAdditionalText("path2.txt", "def");
driver = driver.ReplaceAdditionalText(secondText, thirdText);
// run, and check that only the paths got re-run
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path2.txt", additionalTextPaths[0]);
Assert.Empty(additionalTextsContents);
}
[Theory]
[CombinatorialData]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput)
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", ""));
ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", ""));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var result = driver.GetRunResult();
Assert.Single(result.Results);
Assert.Empty(result.Results[0].Diagnostics);
// verify the expected outputs were generated
// NOTE: adding new output types will cause this test to fail. Update above as needed.
foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind)))
{
if (kind == IncrementalGeneratorOutputKind.None)
continue;
if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind))
{
Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind);
}
else
{
Assert.Contains(result.Results[0].GeneratedSources, isTextForKind);
}
bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs";
}
}
[Fact]
public void Metadata_References_Provider()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
var metadataRefs = new[] {
MetadataReference.CreateFromAssemblyInternal(this.GetType().Assembly),
MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly)
};
Compilation compilation = CreateEmptyCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions, references: metadataRefs);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<string?> referenceList = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.MetadataReferencesProvider, (spc, r) => { referenceList.Add(r.Display); });
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(referenceList[0], metadataRefs[0].Display);
Assert.Equal(referenceList[1], metadataRefs[1].Display);
// re-run and check we didn't see anything new
referenceList.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(referenceList);
// Modify the reference
var modifiedRef = metadataRefs[0].WithAliases(new[] { "Alias " });
metadataRefs[0] = modifiedRef;
compilation = compilation.WithReferences(metadataRefs);
driver = driver.RunGenerators(compilation);
Assert.Single(referenceList, modifiedRef.Display);
}
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/VisualStudio/Core/Def/Implementation/Watson/WatsonReporter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Reflection;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.VisualStudio.LanguageServices.Telemetry;
using Microsoft.VisualStudio.Telemetry;
namespace Microsoft.CodeAnalysis.ErrorReporting
{
internal static class WatsonReporter
{
private static Dictionary<string, string>? s_capturedFileContent;
private static readonly object _guard = new();
private static ImmutableArray<TelemetrySession> s_telemetrySessions = ImmutableArray<TelemetrySession>.Empty;
private static ImmutableArray<TraceSource> s_loggers = ImmutableArray<TraceSource>.Empty;
public static void InitializeFatalErrorHandlers()
{
// Set both handlers to non-fatal Watson. Never fail-fast the ServiceHub process.
// Any exception that is not recovered from shall be propagated and communicated to the client.
var nonFatalHandler = new Action<Exception>(ReportNonFatal);
var fatalHandler = nonFatalHandler;
FatalError.Handler = fatalHandler;
FatalError.NonFatalHandler = nonFatalHandler;
// We also must set the handlers for the compiler layer as well.
var compilerAssembly = typeof(Compilation).Assembly;
var compilerFatalErrorType = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true)!;
var compilerFatalErrorHandlerProperty = compilerFatalErrorType.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public)!;
var compilerNonFatalErrorHandlerProperty = compilerFatalErrorType.GetProperty(nameof(FatalError.NonFatalHandler), BindingFlags.Static | BindingFlags.Public)!;
compilerFatalErrorHandlerProperty.SetValue(null, fatalHandler);
compilerNonFatalErrorHandlerProperty.SetValue(null, nonFatalHandler);
}
public static void RegisterTelemetrySesssion(TelemetrySession session)
{
lock (_guard)
{
s_telemetrySessions = s_telemetrySessions.Add(session);
}
}
public static void UnregisterTelemetrySesssion(TelemetrySession session)
{
lock (_guard)
{
s_telemetrySessions = s_telemetrySessions.Remove(session);
}
}
public static void RegisterLogger(TraceSource logger)
{
lock (_guard)
{
s_loggers = s_loggers.Add(logger);
}
}
public static void UnregisterLogger(TraceSource logger)
{
lock (_guard)
{
s_loggers = s_loggers.Remove(logger);
}
}
/// <summary>
/// Report Non-Fatal Watson for a given unhandled exception.
/// </summary>
/// <param name="exception">Exception that triggered this non-fatal error</param>
public static void ReportNonFatal(Exception exception)
{
try
{
var emptyCallstack = exception.SetCallstackIfEmpty();
var currentProcess = Process.GetCurrentProcess();
// write the exception to a log file:
var logMessage = $"[{currentProcess.ProcessName}:{currentProcess.Id}] Unexpected exception: {exception}";
foreach (var logger in s_loggers)
{
logger.TraceEvent(TraceEventType.Error, 1, logMessage);
}
var faultEvent = new FaultEvent(
eventName: FunctionId.NonFatalWatson.GetEventName(),
description: GetDescription(exception),
FaultSeverity.Diagnostic,
exceptionObject: exception,
gatherEventDetails: faultUtility =>
{
if (faultUtility is FaultEvent { IsIncludedInWatsonSample: true })
{
// add ServiceHub log files:
foreach (var path in CollectServiceHubLogFilePaths())
{
faultUtility.AddFile(path);
}
}
// Returning "0" signals that, if sampled, we should send data to Watson.
// Any other value will cancel the Watson report. We never want to trigger a process dump manually,
// we'll let TargetedNotifications determine if a dump should be collected.
// See https://aka.ms/roslynnfwdocs for more details
return 0;
});
// add extra bucket parameters to bucket better in NFW
// we do it here so that it gets bucketted better in both
// watson and telemetry.
faultEvent.SetExtraParameters(exception, emptyCallstack);
foreach (var session in s_telemetrySessions)
{
session.PostEvent(faultEvent);
}
}
catch (OutOfMemoryException)
{
FailFast.OnFatalException(exception);
}
catch (Exception e)
{
FailFast.OnFatalException(e);
}
}
private static string GetDescription(Exception exception)
{
const string CodeAnalysisNamespace = nameof(Microsoft) + "." + nameof(CodeAnalysis);
// Be resilient to failing here. If we can't get a suitable name, just fall back to the standard name we
// used to report.
try
{
// walk up the stack looking for the first call from a type that isn't in the ErrorReporting namespace.
foreach (var frame in new StackTrace(exception).GetFrames())
{
var method = frame?.GetMethod();
var methodName = method?.Name;
if (methodName == null)
continue;
var declaringTypeName = method?.DeclaringType?.FullName;
if (declaringTypeName == null)
continue;
if (!declaringTypeName.StartsWith(CodeAnalysisNamespace))
continue;
return declaringTypeName + "." + methodName;
}
}
catch
{
}
return "Roslyn NonFatal Watson";
}
private static List<string> CollectServiceHubLogFilePaths()
{
var paths = new List<string>();
try
{
var logPath = Path.Combine(Path.GetTempPath(), "servicehub", "logs");
if (!Directory.Exists(logPath))
{
return paths;
}
// attach all log files that are modified less than 1 day before.
var now = DateTime.UtcNow;
var oneDay = TimeSpan.FromDays(1);
foreach (var path in Directory.EnumerateFiles(logPath, "*.log"))
{
try
{
var name = Path.GetFileNameWithoutExtension(path);
// TODO: https://github.com/dotnet/roslyn/issues/42582
// name our services more consistently to simplify filtering
// filter logs that are not relevant to Roslyn investigation
if (!name.Contains("-" + ServiceDescriptors.ServiceNameTopLevelPrefix) &&
!name.Contains("-" + ServiceDescriptors.Prefix) &&
!name.Contains("-CodeLens") &&
!name.Contains("-ManagedLanguage.IDE.RemoteHostClient") &&
!name.Contains("-hub"))
{
continue;
}
var lastWrite = File.GetLastWriteTimeUtc(path);
if (now - lastWrite > oneDay)
{
continue;
}
paths.Add(path);
}
catch
{
// ignore file that can't be accessed
}
}
}
catch (Exception)
{
// ignore failures
}
return paths;
}
private static void CaptureFilesInMemory(IEnumerable<string> paths)
{
s_capturedFileContent = new Dictionary<string, string>();
foreach (var path in paths)
{
try
{
s_capturedFileContent[path] = File.ReadAllText(path);
}
catch
{
// ignore file that can't be read
}
}
}
}
internal enum WatsonSeverity
{
/// <summary>
/// Indicate that this watson is informative and not urgent
/// </summary>
Default,
/// <summary>
/// Indicate that this watson is critical and need to be addressed soon
/// </summary>
Critical,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Reflection;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.VisualStudio.LanguageServices.Telemetry;
using Microsoft.VisualStudio.Telemetry;
namespace Microsoft.CodeAnalysis.ErrorReporting
{
internal static class WatsonReporter
{
private static Dictionary<string, string>? s_capturedFileContent;
private static readonly object _guard = new();
private static ImmutableArray<TelemetrySession> s_telemetrySessions = ImmutableArray<TelemetrySession>.Empty;
private static ImmutableArray<TraceSource> s_loggers = ImmutableArray<TraceSource>.Empty;
public static void InitializeFatalErrorHandlers()
{
// Set both handlers to non-fatal Watson. Never fail-fast the ServiceHub process.
// Any exception that is not recovered from shall be propagated and communicated to the client.
var nonFatalHandler = new Action<Exception>(ReportNonFatal);
var fatalHandler = nonFatalHandler;
FatalError.Handler = fatalHandler;
FatalError.NonFatalHandler = nonFatalHandler;
// We also must set the handlers for the compiler layer as well.
var compilerAssembly = typeof(Compilation).Assembly;
var compilerFatalErrorType = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true)!;
var compilerFatalErrorHandlerProperty = compilerFatalErrorType.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public)!;
var compilerNonFatalErrorHandlerProperty = compilerFatalErrorType.GetProperty(nameof(FatalError.NonFatalHandler), BindingFlags.Static | BindingFlags.Public)!;
compilerFatalErrorHandlerProperty.SetValue(null, fatalHandler);
compilerNonFatalErrorHandlerProperty.SetValue(null, nonFatalHandler);
}
public static void RegisterTelemetrySesssion(TelemetrySession session)
{
lock (_guard)
{
s_telemetrySessions = s_telemetrySessions.Add(session);
}
}
public static void UnregisterTelemetrySesssion(TelemetrySession session)
{
lock (_guard)
{
s_telemetrySessions = s_telemetrySessions.Remove(session);
}
}
public static void RegisterLogger(TraceSource logger)
{
lock (_guard)
{
s_loggers = s_loggers.Add(logger);
}
}
public static void UnregisterLogger(TraceSource logger)
{
lock (_guard)
{
s_loggers = s_loggers.Remove(logger);
}
}
/// <summary>
/// Report Non-Fatal Watson for a given unhandled exception.
/// </summary>
/// <param name="exception">Exception that triggered this non-fatal error</param>
public static void ReportNonFatal(Exception exception)
{
try
{
var emptyCallstack = exception.SetCallstackIfEmpty();
var currentProcess = Process.GetCurrentProcess();
// write the exception to a log file:
var logMessage = $"[{currentProcess.ProcessName}:{currentProcess.Id}] Unexpected exception: {exception}";
foreach (var logger in s_loggers)
{
logger.TraceEvent(TraceEventType.Error, 1, logMessage);
}
var faultEvent = new FaultEvent(
eventName: FunctionId.NonFatalWatson.GetEventName(),
description: GetDescription(exception),
FaultSeverity.Diagnostic,
exceptionObject: exception,
gatherEventDetails: faultUtility =>
{
if (faultUtility is FaultEvent { IsIncludedInWatsonSample: true })
{
// add ServiceHub log files:
foreach (var path in CollectServiceHubLogFilePaths())
{
faultUtility.AddFile(path);
}
}
// Returning "0" signals that, if sampled, we should send data to Watson.
// Any other value will cancel the Watson report. We never want to trigger a process dump manually,
// we'll let TargetedNotifications determine if a dump should be collected.
// See https://aka.ms/roslynnfwdocs for more details
return 0;
});
// add extra bucket parameters to bucket better in NFW
// we do it here so that it gets bucketted better in both
// watson and telemetry.
faultEvent.SetExtraParameters(exception, emptyCallstack);
foreach (var session in s_telemetrySessions)
{
session.PostEvent(faultEvent);
}
}
catch (OutOfMemoryException)
{
FailFast.OnFatalException(exception);
}
catch (Exception e)
{
FailFast.OnFatalException(e);
}
}
private static string GetDescription(Exception exception)
{
const string CodeAnalysisNamespace = nameof(Microsoft) + "." + nameof(CodeAnalysis);
// Be resilient to failing here. If we can't get a suitable name, just fall back to the standard name we
// used to report.
try
{
// walk up the stack looking for the first call from a type that isn't in the ErrorReporting namespace.
foreach (var frame in new StackTrace(exception).GetFrames())
{
var method = frame?.GetMethod();
var methodName = method?.Name;
if (methodName == null)
continue;
var declaringTypeName = method?.DeclaringType?.FullName;
if (declaringTypeName == null)
continue;
if (!declaringTypeName.StartsWith(CodeAnalysisNamespace))
continue;
return declaringTypeName + "." + methodName;
}
}
catch
{
}
return "Roslyn NonFatal Watson";
}
private static List<string> CollectServiceHubLogFilePaths()
{
var paths = new List<string>();
try
{
var logPath = Path.Combine(Path.GetTempPath(), "servicehub", "logs");
if (!Directory.Exists(logPath))
{
return paths;
}
// attach all log files that are modified less than 1 day before.
var now = DateTime.UtcNow;
var oneDay = TimeSpan.FromDays(1);
foreach (var path in Directory.EnumerateFiles(logPath, "*.log"))
{
try
{
var name = Path.GetFileNameWithoutExtension(path);
// TODO: https://github.com/dotnet/roslyn/issues/42582
// name our services more consistently to simplify filtering
// filter logs that are not relevant to Roslyn investigation
if (!name.Contains("-" + ServiceDescriptors.ServiceNameTopLevelPrefix) &&
!name.Contains("-" + ServiceDescriptors.Prefix) &&
!name.Contains("-CodeLens") &&
!name.Contains("-ManagedLanguage.IDE.RemoteHostClient") &&
!name.Contains("-hub"))
{
continue;
}
var lastWrite = File.GetLastWriteTimeUtc(path);
if (now - lastWrite > oneDay)
{
continue;
}
paths.Add(path);
}
catch
{
// ignore file that can't be accessed
}
}
}
catch (Exception)
{
// ignore failures
}
return paths;
}
private static void CaptureFilesInMemory(IEnumerable<string> paths)
{
s_capturedFileContent = new Dictionary<string, string>();
foreach (var path in paths)
{
try
{
s_capturedFileContent[path] = File.ReadAllText(path);
}
catch
{
// ignore file that can't be read
}
}
}
}
internal enum WatsonSeverity
{
/// <summary>
/// Indicate that this watson is informative and not urgent
/// </summary>
Default,
/// <summary>
/// Indicate that this watson is critical and need to be addressed soon
/// </summary>
Critical,
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/CastExpressionSyntaxExtensions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module CastExpressionSyntaxExtensions
<Extension>
Public Function Uncast(cast As CastExpressionSyntax) As ExpressionSyntax
Return Uncast(cast, cast.Expression)
End Function
<Extension>
Public Function Uncast(cast As PredefinedCastExpressionSyntax) As ExpressionSyntax
Return Uncast(cast, cast.Expression)
End Function
Private Function Uncast(castNode As ExpressionSyntax, innerNode As ExpressionSyntax) As ExpressionSyntax
Dim resultNode = innerNode.WithTriviaFrom(castNode)
resultNode = SimplificationHelpers.CopyAnnotations(castNode, resultNode)
Return resultNode
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module CastExpressionSyntaxExtensions
<Extension>
Public Function Uncast(cast As CastExpressionSyntax) As ExpressionSyntax
Return Uncast(cast, cast.Expression)
End Function
<Extension>
Public Function Uncast(cast As PredefinedCastExpressionSyntax) As ExpressionSyntax
Return Uncast(cast, cast.Expression)
End Function
Private Function Uncast(castNode As ExpressionSyntax, innerNode As ExpressionSyntax) As ExpressionSyntax
Dim resultNode = innerNode.WithTriviaFrom(castNode)
resultNode = SimplificationHelpers.CopyAnnotations(castNode, resultNode)
Return resultNode
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Workspaces/VisualBasic/Portable/CodeGeneration/AttributeGenerator.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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module AttributeGenerator
Public Function GenerateAttributeBlocks(attributes As ImmutableArray(Of AttributeData), options As CodeGenerationOptions, Optional target As SyntaxToken? = Nothing) As SyntaxList(Of AttributeListSyntax)
If Not attributes.Any() Then
Return Nothing
End If
Return SyntaxFactory.List(Of AttributeListSyntax)(attributes.OrderBy(Function(a) a.AttributeClass.Name).Select(Function(a) GenerateAttributeBlock(a, options, target)))
End Function
Private Function GenerateAttributeBlock(attribute As AttributeData, options As CodeGenerationOptions, target As SyntaxToken?) As AttributeListSyntax
Return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(GenerateAttribute(attribute, options, target)))
End Function
Private Function GenerateAttribute(attribute As AttributeData, options As CodeGenerationOptions, target As SyntaxToken?) As AttributeSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForAttribute(Of AttributeSyntax)(attribute, options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax
End If
Return SyntaxFactory.Attribute(If(target.HasValue, SyntaxFactory.AttributeTarget(target.Value), Nothing),
attribute.AttributeClass.GenerateTypeSyntax(),
GenerateArgumentList(attribute))
End Function
Private Function GenerateArgumentList(attribute As AttributeData) As ArgumentListSyntax
If attribute.ConstructorArguments.Length = 0 AndAlso attribute.NamedArguments.Length = 0 Then
Return Nothing
End If
Dim arguments = New List(Of ArgumentSyntax)
arguments.AddRange(attribute.ConstructorArguments.Select(
Function(a) SyntaxFactory.SimpleArgument(GenerateExpression(a))))
arguments.AddRange(attribute.NamedArguments.Select(
Function(kvp) SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(kvp.Key.ToIdentifierName()), GenerateExpression(kvp.Value))))
Return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Module AttributeGenerator
Public Function GenerateAttributeBlocks(attributes As ImmutableArray(Of AttributeData), options As CodeGenerationOptions, Optional target As SyntaxToken? = Nothing) As SyntaxList(Of AttributeListSyntax)
If Not attributes.Any() Then
Return Nothing
End If
Return SyntaxFactory.List(Of AttributeListSyntax)(attributes.OrderBy(Function(a) a.AttributeClass.Name).Select(Function(a) GenerateAttributeBlock(a, options, target)))
End Function
Private Function GenerateAttributeBlock(attribute As AttributeData, options As CodeGenerationOptions, target As SyntaxToken?) As AttributeListSyntax
Return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(GenerateAttribute(attribute, options, target)))
End Function
Private Function GenerateAttribute(attribute As AttributeData, options As CodeGenerationOptions, target As SyntaxToken?) As AttributeSyntax
Dim reusableSyntax = GetReuseableSyntaxNodeForAttribute(Of AttributeSyntax)(attribute, options)
If reusableSyntax IsNot Nothing Then
Return reusableSyntax
End If
Return SyntaxFactory.Attribute(If(target.HasValue, SyntaxFactory.AttributeTarget(target.Value), Nothing),
attribute.AttributeClass.GenerateTypeSyntax(),
GenerateArgumentList(attribute))
End Function
Private Function GenerateArgumentList(attribute As AttributeData) As ArgumentListSyntax
If attribute.ConstructorArguments.Length = 0 AndAlso attribute.NamedArguments.Length = 0 Then
Return Nothing
End If
Dim arguments = New List(Of ArgumentSyntax)
arguments.AddRange(attribute.ConstructorArguments.Select(
Function(a) SyntaxFactory.SimpleArgument(GenerateExpression(a))))
arguments.AddRange(attribute.NamedArguments.Select(
Function(kvp) SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(kvp.Key.ToIdentifierName()), GenerateExpression(kvp.Value))))
Return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ExplicitInterfaceMethodReferenceFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal sealed class ExplicitInterfaceMethodReferenceFinder : AbstractReferenceFinder<IMethodSymbol>
{
protected override bool CanFind(IMethodSymbol symbol)
=> symbol.MethodKind == MethodKind.ExplicitInterfaceImplementation;
protected sealed override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
IMethodSymbol symbol,
HashSet<string>? globalAliases,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// An explicit method can't be referenced anywhere.
return SpecializedTasks.EmptyImmutableArray<Document>();
}
protected sealed override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
IMethodSymbol symbol,
HashSet<string>? globalAliases,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// An explicit method can't be referenced anywhere.
return new ValueTask<ImmutableArray<FinderLocation>>(ImmutableArray<FinderLocation>.Empty);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols.Finders
{
internal sealed class ExplicitInterfaceMethodReferenceFinder : AbstractReferenceFinder<IMethodSymbol>
{
protected override bool CanFind(IMethodSymbol symbol)
=> symbol.MethodKind == MethodKind.ExplicitInterfaceImplementation;
protected sealed override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
IMethodSymbol symbol,
HashSet<string>? globalAliases,
Project project,
IImmutableSet<Document>? documents,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// An explicit method can't be referenced anywhere.
return SpecializedTasks.EmptyImmutableArray<Document>();
}
protected sealed override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync(
IMethodSymbol symbol,
HashSet<string>? globalAliases,
Document document,
SemanticModel semanticModel,
FindReferencesSearchOptions options,
CancellationToken cancellationToken)
{
// An explicit method can't be referenced anywhere.
return new ValueTask<ImmutableArray<FinderLocation>>(ImmutableArray<FinderLocation>.Empty);
}
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/CSharp/Portable/Parser/DocumentationCommentParser.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
// TODO: The Xml parser recognizes most commonplace XML, according to the XML spec.
// It does not recognize the following:
//
// * Document Type Definition
// <!DOCTYPE ... >
// * Element Type Declaration, Attribute-List Declarations, Entity Declarations, Notation Declarations
// <!ELEMENT ... >
// <!ATTLIST ... >
// <!ENTITY ... >
// <!NOTATION ... >
// * Conditional Sections
// <![INCLUDE[ ... ]]>
// <![IGNORE[ ... ]]>
//
// This probably does not matter. However, if it becomes necessary to recognize any
// of these bits of XML, the most sensible thing to do is probably to scan them without
// trying to understand them, e.g. like comments or CDATA, so that they are available
// to whoever processes these comments and do not produce an error.
internal class DocumentationCommentParser : SyntaxParser
{
private readonly SyntaxListPool _pool = new SyntaxListPool();
private bool _isDelimited;
internal DocumentationCommentParser(Lexer lexer, LexerMode modeflags)
: base(lexer, LexerMode.XmlDocComment | LexerMode.XmlDocCommentLocationStart | modeflags, null, null, true)
{
_isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0;
}
internal void ReInitialize(LexerMode modeflags)
{
base.ReInitialize();
this.Mode = LexerMode.XmlDocComment | LexerMode.XmlDocCommentLocationStart | modeflags;
_isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0;
}
private LexerMode SetMode(LexerMode mode)
{
var tmp = this.Mode;
this.Mode = mode | (tmp & (LexerMode.MaskXmlDocCommentLocation | LexerMode.MaskXmlDocCommentStyle));
return tmp;
}
private void ResetMode(LexerMode mode)
{
this.Mode = mode;
}
public DocumentationCommentTriviaSyntax ParseDocumentationComment(out bool isTerminated)
{
var nodes = _pool.Allocate<XmlNodeSyntax>();
try
{
this.ParseXmlNodes(nodes);
// It's possible that we finish parsing the xml, and we are still left in the middle
// of an Xml comment. For example,
//
// /// <goo></goo></uhoh>
// ^
// In this case, we stop at the caret. We need to ensure that we consume the remainder
// of the doc comment here, since otherwise we will return the lexer to the state
// where it recognizes C# tokens, which means that C# parser will get the </uhoh>,
// which is not at all what we want.
if (this.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken)
{
this.ParseRemainder(nodes);
}
var eoc = this.EatToken(SyntaxKind.EndOfDocumentationCommentToken);
isTerminated = !_isDelimited || (eoc.LeadingTrivia.Count > 0 && eoc.LeadingTrivia[eoc.LeadingTrivia.Count - 1].ToString() == "*/");
SyntaxKind kind = _isDelimited ? SyntaxKind.MultiLineDocumentationCommentTrivia : SyntaxKind.SingleLineDocumentationCommentTrivia;
return SyntaxFactory.DocumentationCommentTrivia(kind, nodes.ToList(), eoc);
}
finally
{
_pool.Free(nodes);
}
}
public void ParseRemainder(SyntaxListBuilder<XmlNodeSyntax> nodes)
{
bool endTag = this.CurrentToken.Kind == SyntaxKind.LessThanSlashToken;
var saveMode = this.SetMode(LexerMode.XmlCDataSectionText);
var textTokens = _pool.Allocate();
try
{
while (this.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken)
{
var token = this.EatToken();
// TODO: It is possible that a non-literal gets in here. ]]>, specifically. Is that ok?
textTokens.Add(token);
}
var allRemainderText = SyntaxFactory.XmlText(textTokens.ToList());
XmlParseErrorCode code = endTag ? XmlParseErrorCode.XML_EndTagNotExpected : XmlParseErrorCode.XML_ExpectedEndOfXml;
allRemainderText = WithAdditionalDiagnostics(allRemainderText, new XmlSyntaxDiagnosticInfo(0, 1, code));
nodes.Add(allRemainderText);
}
finally
{
_pool.Free(textTokens);
}
this.ResetMode(saveMode);
}
private void ParseXmlNodes(SyntaxListBuilder<XmlNodeSyntax> nodes)
{
while (true)
{
var node = this.ParseXmlNode();
if (node == null)
{
return;
}
nodes.Add(node);
}
}
private XmlNodeSyntax ParseXmlNode()
{
switch (this.CurrentToken.Kind)
{
case SyntaxKind.XmlTextLiteralToken:
case SyntaxKind.XmlTextLiteralNewLineToken:
case SyntaxKind.XmlEntityLiteralToken:
return this.ParseXmlText();
case SyntaxKind.LessThanToken:
return this.ParseXmlElement();
case SyntaxKind.XmlCommentStartToken:
return this.ParseXmlComment();
case SyntaxKind.XmlCDataStartToken:
return this.ParseXmlCDataSection();
case SyntaxKind.XmlProcessingInstructionStartToken:
return this.ParseXmlProcessingInstruction();
case SyntaxKind.EndOfDocumentationCommentToken:
return null;
default:
// This means we have some unrecognized token. We probably need to give an error.
return null;
}
}
private bool IsXmlNodeStartOrStop()
{
switch (this.CurrentToken.Kind)
{
case SyntaxKind.LessThanToken:
case SyntaxKind.LessThanSlashToken:
case SyntaxKind.XmlCommentStartToken:
case SyntaxKind.XmlCDataStartToken:
case SyntaxKind.XmlProcessingInstructionStartToken:
case SyntaxKind.GreaterThanToken:
case SyntaxKind.SlashGreaterThanToken:
case SyntaxKind.EndOfDocumentationCommentToken:
return true;
default:
return false;
}
}
private XmlNodeSyntax ParseXmlText()
{
var textTokens = _pool.Allocate();
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken
|| this.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken)
{
textTokens.Add(this.EatToken());
}
var list = textTokens.ToList();
_pool.Free(textTokens);
return SyntaxFactory.XmlText(list);
}
private XmlNodeSyntax ParseXmlElement()
{
var lessThan = this.EatToken(SyntaxKind.LessThanToken); // guaranteed
var saveMode = this.SetMode(LexerMode.XmlElementTag);
var name = this.ParseXmlName();
if (lessThan.GetTrailingTriviaWidth() > 0 || name.GetLeadingTriviaWidth() > 0)
{
// The Xml spec disallows whitespace here: STag ::= '<' Name (S Attribute)* S? '>'
name = this.WithXmlParseError(name, XmlParseErrorCode.XML_InvalidWhitespace);
}
var attrs = _pool.Allocate<XmlAttributeSyntax>();
try
{
this.ParseXmlAttributes(ref name, attrs);
if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken)
{
var startTag = SyntaxFactory.XmlElementStartTag(lessThan, name, attrs, this.EatToken());
this.SetMode(LexerMode.XmlDocComment);
var nodes = _pool.Allocate<XmlNodeSyntax>();
try
{
this.ParseXmlNodes(nodes);
XmlNameSyntax endName;
SyntaxToken greaterThan;
// end tag
var lessThanSlash = this.EatToken(SyntaxKind.LessThanSlashToken, reportError: false);
// If we didn't see "</", then we can't really be confident that this is actually an end tag,
// so just insert a missing one.
if (lessThanSlash.IsMissing)
{
this.ResetMode(saveMode);
lessThanSlash = this.WithXmlParseError(lessThanSlash, XmlParseErrorCode.XML_EndTagExpected, name.ToString());
endName = SyntaxFactory.XmlName(prefix: null, localName: SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
greaterThan = SyntaxFactory.MissingToken(SyntaxKind.GreaterThanToken);
}
else
{
this.SetMode(LexerMode.XmlElementTag);
endName = this.ParseXmlName();
if (lessThanSlash.GetTrailingTriviaWidth() > 0 || endName.GetLeadingTriviaWidth() > 0)
{
// The Xml spec disallows whitespace here: STag ::= '<' Name (S Attribute)* S? '>'
endName = this.WithXmlParseError(endName, XmlParseErrorCode.XML_InvalidWhitespace);
}
if (!endName.IsMissing && !MatchingXmlNames(name, endName))
{
endName = this.WithXmlParseError(endName, XmlParseErrorCode.XML_ElementTypeMatch, endName.ToString(), name.ToString());
}
// if we don't see the greater than token then skip the badness until we do or abort
if (this.CurrentToken.Kind != SyntaxKind.GreaterThanToken)
{
this.SkipBadTokens(ref endName, null,
p => p.CurrentToken.Kind != SyntaxKind.GreaterThanToken,
p => p.IsXmlNodeStartOrStop(),
XmlParseErrorCode.XML_InvalidToken
);
}
greaterThan = this.EatToken(SyntaxKind.GreaterThanToken);
}
var endTag = SyntaxFactory.XmlElementEndTag(lessThanSlash, endName, greaterThan);
this.ResetMode(saveMode);
return SyntaxFactory.XmlElement(startTag, nodes.ToList(), endTag);
}
finally
{
_pool.Free(nodes);
}
}
else
{
var slashGreater = this.EatToken(SyntaxKind.SlashGreaterThanToken, false);
if (slashGreater.IsMissing && !name.IsMissing)
{
slashGreater = this.WithXmlParseError(slashGreater, XmlParseErrorCode.XML_ExpectedEndOfTag, name.ToString());
}
this.ResetMode(saveMode);
return SyntaxFactory.XmlEmptyElement(lessThan, name, attrs, slashGreater);
}
}
finally
{
_pool.Free(attrs);
}
}
private static bool MatchingXmlNames(XmlNameSyntax name, XmlNameSyntax endName)
{
// PERF: because of deduplication we often get the same name for name and endName,
// so we will check for such case first before materializing text for entire nodes
// and comparing that.
if (name == endName)
{
return true;
}
// before doing ToString, check if
// all nodes contributing to ToString are recursively the same
// NOTE: leading and trailing trivia do not contribute to ToString
if (!name.HasLeadingTrivia &&
!endName.HasTrailingTrivia &&
name.IsEquivalentTo(endName))
{
return true;
}
return name.ToString() == endName.ToString();
}
// assuming this is not used concurrently
private readonly HashSet<string> _attributesSeen = new HashSet<string>();
private void ParseXmlAttributes(ref XmlNameSyntax elementName, SyntaxListBuilder<XmlAttributeSyntax> attrs)
{
_attributesSeen.Clear();
while (true)
{
if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken)
{
var attr = this.ParseXmlAttribute(elementName);
string attrName = attr.Name.ToString();
if (_attributesSeen.Contains(attrName))
{
attr = this.WithXmlParseError(attr, XmlParseErrorCode.XML_DuplicateAttribute, attrName);
}
else
{
_attributesSeen.Add(attrName);
}
attrs.Add(attr);
}
else
{
var skip = this.SkipBadTokens(ref elementName, attrs,
// not expected condition
p => p.CurrentToken.Kind != SyntaxKind.IdentifierName,
// abort condition (looks like something we might understand later)
p => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken
|| p.CurrentToken.Kind == SyntaxKind.SlashGreaterThanToken
|| p.CurrentToken.Kind == SyntaxKind.LessThanToken
|| p.CurrentToken.Kind == SyntaxKind.LessThanSlashToken
|| p.CurrentToken.Kind == SyntaxKind.EndOfDocumentationCommentToken
|| p.CurrentToken.Kind == SyntaxKind.EndOfFileToken,
XmlParseErrorCode.XML_InvalidToken
);
if (skip == SkipResult.Abort)
{
break;
}
}
}
}
private enum SkipResult
{
Continue,
Abort
}
private SkipResult SkipBadTokens<T>(
ref T startNode,
SyntaxListBuilder list,
Func<DocumentationCommentParser, bool> isNotExpectedFunction,
Func<DocumentationCommentParser, bool> abortFunction,
XmlParseErrorCode error
) where T : CSharpSyntaxNode
{
var badTokens = default(SyntaxListBuilder<SyntaxToken>);
bool hasError = false;
try
{
SkipResult result = SkipResult.Continue;
while (isNotExpectedFunction(this))
{
if (abortFunction(this))
{
result = SkipResult.Abort;
break;
}
if (badTokens.IsNull)
{
badTokens = _pool.Allocate<SyntaxToken>();
}
var token = this.EatToken();
if (!hasError)
{
token = this.WithXmlParseError(token, error, token.ToString());
hasError = true;
}
badTokens.Add(token);
}
if (!badTokens.IsNull && badTokens.Count > 0)
{
// use skipped text since cannot nest structured trivia under structured trivia
if (list == null || list.Count == 0)
{
startNode = AddTrailingSkippedSyntax(startNode, badTokens.ToListNode());
}
else
{
list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], badTokens.ToListNode());
}
return result;
}
else
{
// somehow we did not consume anything, so tell caller to abort parse rule
return SkipResult.Abort;
}
}
finally
{
if (!badTokens.IsNull)
{
_pool.Free(badTokens);
}
}
}
private XmlAttributeSyntax ParseXmlAttribute(XmlNameSyntax elementName)
{
var attrName = this.ParseXmlName();
if (attrName.GetLeadingTriviaWidth() == 0)
{
// The Xml spec requires whitespace here: STag ::= '<' Name (S Attribute)* S? '>'
attrName = this.WithXmlParseError(attrName, XmlParseErrorCode.XML_WhitespaceMissing);
}
var equals = this.EatToken(SyntaxKind.EqualsToken, false);
if (equals.IsMissing)
{
equals = this.WithXmlParseError(equals, XmlParseErrorCode.XML_MissingEqualsAttribute);
switch (this.CurrentToken.Kind)
{
case SyntaxKind.SingleQuoteToken:
case SyntaxKind.DoubleQuoteToken:
// There could be a value coming up, let's keep parsing.
break;
default:
// This is probably not a complete attribute.
return SyntaxFactory.XmlTextAttribute(
attrName,
equals,
SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken),
default(SyntaxList<SyntaxToken>),
SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken));
}
}
SyntaxToken startQuote;
SyntaxToken endQuote;
string attrNameText = attrName.LocalName.ValueText;
bool hasNoPrefix = attrName.Prefix == null;
if (hasNoPrefix && DocumentationCommentXmlNames.AttributeEquals(attrNameText, DocumentationCommentXmlNames.CrefAttributeName) &&
!IsVerbatimCref())
{
CrefSyntax cref;
this.ParseCrefAttribute(out startQuote, out cref, out endQuote);
return SyntaxFactory.XmlCrefAttribute(attrName, equals, startQuote, cref, endQuote);
}
else if (hasNoPrefix && DocumentationCommentXmlNames.AttributeEquals(attrNameText, DocumentationCommentXmlNames.NameAttributeName) &&
XmlElementSupportsNameAttribute(elementName))
{
IdentifierNameSyntax identifier;
this.ParseNameAttribute(out startQuote, out identifier, out endQuote);
return SyntaxFactory.XmlNameAttribute(attrName, equals, startQuote, identifier, endQuote);
}
else
{
var textTokens = _pool.Allocate<SyntaxToken>();
try
{
this.ParseXmlAttributeText(out startQuote, textTokens, out endQuote);
return SyntaxFactory.XmlTextAttribute(attrName, equals, startQuote, textTokens, endQuote);
}
finally
{
_pool.Free(textTokens);
}
}
}
private static bool XmlElementSupportsNameAttribute(XmlNameSyntax elementName)
{
if (elementName.Prefix != null)
{
return false;
}
string localName = elementName.LocalName.ValueText;
return
DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.ParameterElementName) ||
DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.ParameterReferenceElementName) ||
DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.TypeParameterElementName) ||
DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.TypeParameterReferenceElementName);
}
private bool IsVerbatimCref()
{
// As in XMLDocWriter::ReplaceReferences, if the first character of the value is not colon and the second character
// is, then don't process the cref - just emit it as-is.
bool isVerbatim = false;
var resetPoint = this.GetResetPoint();
SyntaxToken openQuote = EatToken(this.CurrentToken.Kind == SyntaxKind.SingleQuoteToken
? SyntaxKind.SingleQuoteToken
: SyntaxKind.DoubleQuoteToken);
// NOTE: Don't need to save mode, since we're already using a reset point.
this.SetMode(LexerMode.XmlCharacter);
SyntaxToken current = this.CurrentToken;
if ((current.Kind == SyntaxKind.XmlTextLiteralToken || current.Kind == SyntaxKind.XmlEntityLiteralToken) &&
current.ValueText != SyntaxFacts.GetText(openQuote.Kind) &&
current.ValueText != ":")
{
EatToken();
current = this.CurrentToken;
if ((current.Kind == SyntaxKind.XmlTextLiteralToken || current.Kind == SyntaxKind.XmlEntityLiteralToken) &&
current.ValueText == ":")
{
isVerbatim = true;
}
}
this.Reset(ref resetPoint);
this.Release(ref resetPoint);
return isVerbatim;
}
private void ParseCrefAttribute(out SyntaxToken startQuote, out CrefSyntax cref, out SyntaxToken endQuote)
{
startQuote = ParseXmlAttributeStartQuote();
SyntaxKind quoteKind = startQuote.Kind;
{
var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken
? LexerMode.XmlCrefQuote
: LexerMode.XmlCrefDoubleQuote);
cref = this.ParseCrefAttributeValue();
this.ResetMode(saveMode);
}
endQuote = ParseXmlAttributeEndQuote(quoteKind);
}
private void ParseNameAttribute(out SyntaxToken startQuote, out IdentifierNameSyntax identifier, out SyntaxToken endQuote)
{
startQuote = ParseXmlAttributeStartQuote();
SyntaxKind quoteKind = startQuote.Kind;
{
var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken
? LexerMode.XmlNameQuote
: LexerMode.XmlNameDoubleQuote);
identifier = this.ParseNameAttributeValue();
this.ResetMode(saveMode);
}
endQuote = ParseXmlAttributeEndQuote(quoteKind);
}
private void ParseXmlAttributeText(out SyntaxToken startQuote, SyntaxListBuilder<SyntaxToken> textTokens, out SyntaxToken endQuote)
{
startQuote = ParseXmlAttributeStartQuote();
SyntaxKind quoteKind = startQuote.Kind;
// NOTE: Being a bit sneaky here - if the width isn't 0, we consumed something else in
// place of the quote and we should continue parsing the attribute.
if (startQuote.IsMissing && startQuote.FullWidth == 0)
{
endQuote = SyntaxFactory.MissingToken(quoteKind);
}
else
{
var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken
? LexerMode.XmlAttributeTextQuote
: LexerMode.XmlAttributeTextDoubleQuote);
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken
|| this.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.LessThanToken)
{
var token = this.EatToken();
if (token.Kind == SyntaxKind.LessThanToken)
{
// TODO: It is possible that a non-literal gets in here. <, specifically. Is that ok?
token = this.WithXmlParseError(token, XmlParseErrorCode.XML_LessThanInAttributeValue);
}
textTokens.Add(token);
}
this.ResetMode(saveMode);
// NOTE: This will never consume a non-ascii quote, since non-ascii quotes
// are legal in the attribute value and are consumed by the preceding loop.
endQuote = ParseXmlAttributeEndQuote(quoteKind);
}
}
private SyntaxToken ParseXmlAttributeStartQuote()
{
if (IsNonAsciiQuotationMark(this.CurrentToken))
{
return SkipNonAsciiQuotationMark();
}
var quoteKind = this.CurrentToken.Kind == SyntaxKind.SingleQuoteToken
? SyntaxKind.SingleQuoteToken
: SyntaxKind.DoubleQuoteToken;
var startQuote = this.EatToken(quoteKind, reportError: false);
if (startQuote.IsMissing)
{
startQuote = this.WithXmlParseError(startQuote, XmlParseErrorCode.XML_StringLiteralNoStartQuote);
}
return startQuote;
}
private SyntaxToken ParseXmlAttributeEndQuote(SyntaxKind quoteKind)
{
if (IsNonAsciiQuotationMark(this.CurrentToken))
{
return SkipNonAsciiQuotationMark();
}
var endQuote = this.EatToken(quoteKind, reportError: false);
if (endQuote.IsMissing)
{
endQuote = this.WithXmlParseError(endQuote, XmlParseErrorCode.XML_StringLiteralNoEndQuote);
}
return endQuote;
}
private SyntaxToken SkipNonAsciiQuotationMark()
{
var quote = SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken);
quote = AddTrailingSkippedSyntax(quote, EatToken());
quote = this.WithXmlParseError(quote, XmlParseErrorCode.XML_StringLiteralNonAsciiQuote);
return quote;
}
/// <summary>
/// These aren't acceptable in place of ASCII quotation marks in XML,
/// but we want to consume them (and produce an appropriate error) if
/// they occur in a place where a quotation mark is legal.
/// </summary>
private static bool IsNonAsciiQuotationMark(SyntaxToken token)
{
return token.Text.Length == 1 && SyntaxFacts.IsNonAsciiQuotationMark(token.Text[0]);
}
private XmlNameSyntax ParseXmlName()
{
var id = this.EatToken(SyntaxKind.IdentifierToken);
XmlPrefixSyntax prefix = null;
if (this.CurrentToken.Kind == SyntaxKind.ColonToken)
{
var colon = this.EatToken();
int prefixTrailingWidth = id.GetTrailingTriviaWidth();
int colonLeadingWidth = colon.GetLeadingTriviaWidth();
if (prefixTrailingWidth > 0 || colonLeadingWidth > 0)
{
// NOTE: offset is relative to full-span start of colon (i.e. before leading trivia).
int offset = -prefixTrailingWidth;
int width = prefixTrailingWidth + colonLeadingWidth;
colon = WithAdditionalDiagnostics(colon, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace));
}
prefix = SyntaxFactory.XmlPrefix(id, colon);
id = this.EatToken(SyntaxKind.IdentifierToken);
int colonTrailingWidth = colon.GetTrailingTriviaWidth();
int localNameLeadingWidth = id.GetLeadingTriviaWidth();
if (colonTrailingWidth > 0 || localNameLeadingWidth > 0)
{
// NOTE: offset is relative to full-span start of identifier (i.e. before leading trivia).
int offset = -colonTrailingWidth;
int width = colonTrailingWidth + localNameLeadingWidth;
id = WithAdditionalDiagnostics(id, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace));
// CONSIDER: Another interpretation would be that the local part of this name is a missing identifier and the identifier
// we've just consumed is actually part of something else (e.g. an attribute name).
}
}
return SyntaxFactory.XmlName(prefix, id);
}
private XmlCommentSyntax ParseXmlComment()
{
var lessThanExclamationMinusMinusToken = this.EatToken(SyntaxKind.XmlCommentStartToken);
var saveMode = this.SetMode(LexerMode.XmlCommentText);
var textTokens = _pool.Allocate<SyntaxToken>();
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken
|| this.CurrentToken.Kind == SyntaxKind.MinusMinusToken)
{
var token = this.EatToken();
if (token.Kind == SyntaxKind.MinusMinusToken)
{
// TODO: It is possible that a non-literal gets in here. --, specifically. Is that ok?
token = this.WithXmlParseError(token, XmlParseErrorCode.XML_IncorrectComment);
}
textTokens.Add(token);
}
var list = textTokens.ToList();
_pool.Free(textTokens);
var minusMinusGreaterThanToken = this.EatToken(SyntaxKind.XmlCommentEndToken);
this.ResetMode(saveMode);
return SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, list, minusMinusGreaterThanToken);
}
private XmlCDataSectionSyntax ParseXmlCDataSection()
{
var startCDataToken = this.EatToken(SyntaxKind.XmlCDataStartToken);
var saveMode = this.SetMode(LexerMode.XmlCDataSectionText);
var textTokens = new SyntaxListBuilder<SyntaxToken>(10);
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken)
{
textTokens.Add(this.EatToken());
}
var endCDataToken = this.EatToken(SyntaxKind.XmlCDataEndToken);
this.ResetMode(saveMode);
return SyntaxFactory.XmlCDataSection(startCDataToken, textTokens, endCDataToken);
}
private XmlProcessingInstructionSyntax ParseXmlProcessingInstruction()
{
var startProcessingInstructionToken = this.EatToken(SyntaxKind.XmlProcessingInstructionStartToken);
var saveMode = this.SetMode(LexerMode.XmlElementTag); //this mode accepts names
var name = this.ParseXmlName();
// NOTE: The XML spec says that name cannot be "xml" (case-insensitive comparison),
// but Dev10 does not enforce this.
this.SetMode(LexerMode.XmlProcessingInstructionText); //this mode consumes text
var textTokens = new SyntaxListBuilder<SyntaxToken>(10);
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken)
{
var textToken = this.EatToken();
// NOTE: The XML spec says that the each text token must begin with a whitespace
// character, but Dev10 does not enforce this.
textTokens.Add(textToken);
}
var endProcessingInstructionToken = this.EatToken(SyntaxKind.XmlProcessingInstructionEndToken);
this.ResetMode(saveMode);
return SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken);
}
protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int length)
{
// NOTE: There are no errors in crefs - only warnings. We accomplish this by wrapping every diagnostic in ErrorCode.WRN_ErrorOverride.
if (InCref)
{
SyntaxDiagnosticInfo rawInfo = base.GetExpectedTokenError(expected, actual, offset, length);
SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(rawInfo.Offset, rawInfo.Width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code);
return crefInfo;
}
switch (expected)
{
case SyntaxKind.IdentifierToken:
return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_ExpectedIdentifier);
default:
return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual));
}
}
protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual)
{
// NOTE: There are no errors in crefs - only warnings. We accomplish this by wrapping every diagnostic in ErrorCode.WRN_ErrorOverride.
if (InCref)
{
int offset, width;
this.GetDiagnosticSpanForMissingToken(out offset, out width);
return GetExpectedTokenError(expected, actual, offset, width);
}
switch (expected)
{
case SyntaxKind.IdentifierToken:
return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_ExpectedIdentifier);
default:
return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual));
}
}
private TNode WithXmlParseError<TNode>(TNode node, XmlParseErrorCode code) where TNode : CSharpSyntaxNode
{
return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code));
}
private TNode WithXmlParseError<TNode>(TNode node, XmlParseErrorCode code, params string[] args) where TNode : CSharpSyntaxNode
{
return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code, args));
}
private SyntaxToken WithXmlParseError(SyntaxToken node, XmlParseErrorCode code, params string[] args)
{
return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code, args));
}
protected override TNode WithAdditionalDiagnostics<TNode>(TNode node, params DiagnosticInfo[] diagnostics)
{
// Don't attach any diagnostics to syntax nodes within a documentation comment if the DocumentationMode
// is not at least Diagnose.
return Options.DocumentationMode >= DocumentationMode.Diagnose
? base.WithAdditionalDiagnostics<TNode>(node, diagnostics)
: node;
}
#region Cref
/// <summary>
/// ACASEY: This grammar is derived from the behavior and sources of the native compiler.
/// Tokens start with underscores (I've cheated for _PredefinedTypeToken, which is not actually a
/// SyntaxKind), "*" indicates "0 or more", "?" indicates "0 or 1", and parentheses are for grouping.
///
/// Cref = CrefType _DotToken CrefMember
/// | CrefType
/// | CrefMember
/// | CrefFirstType _OpenParenToken CrefParameterList? _CloseParenToken
/// CrefName = _IdentifierToken (_LessThanToken _IdentifierToken (_CommaToken _IdentifierToken)* _GreaterThanToken)?
/// CrefFirstType = ((_IdentifierToken _ColonColonToken)? CrefName)
/// | _PredefinedTypeToken
/// CrefType = CrefFirstType (_DotToken CrefName)*
/// CrefMember = CrefName (_OpenParenToken CrefParameterList? _CloseParenToken)?
/// | _ThisKeyword (_OpenBracketToken CrefParameterList _CloseBracketToken)?
/// | _OperatorKeyword _OperatorToken (_OpenParenToken CrefParameterList? _CloseParenToken)?
/// | (_ImplicitKeyword | _ExplicitKeyword) _OperatorKeyword CrefParameterType (_OpenParenToken CrefParameterList? _CloseParenToken)?
/// CrefParameterList = CrefParameter (_CommaToken CrefParameter)*
/// CrefParameter = (_RefKeyword | _OutKeyword)? CrefParameterType
/// CrefParameterType = CrefParameterType2 _QuestionToken? _AsteriskToken* (_OpenBracketToken _CommaToken* _CloseBracketToken)*
/// CrefParameterType2 = (((_IdentifierToken _ColonColonToken)? CrefParameterType3) | _PredefinedTypeToken) (_DotToken CrefParameterType3)*
/// CrefParameterType3 = _IdentifierToken (_LessThanToken CrefParameterType (_CommaToken CrefParameterType)* _GreaterThanToken)?
///
/// NOTE: type parameters, not type arguments
/// NOTE: the first production of Cref is preferred to the other two
/// NOTE: pointer, array, and nullable types only work in parameters
/// NOTE: CrefParameterType2 and CrefParameterType3 correspond to CrefType and CrefName, respectively.
/// Since the only difference is that they accept non-identifier type arguments, this is accomplished
/// using parameters on the parsing methods (rather than whole new methods).
/// </summary>
private CrefSyntax ParseCrefAttributeValue()
{
CrefSyntax result;
TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: true, checkForMember: true);
if (type == null)
{
result = ParseMemberCref();
}
else if (IsEndOfCrefAttribute)
{
result = SyntaxFactory.TypeCref(type);
}
else if (type.Kind != SyntaxKind.QualifiedName && this.CurrentToken.Kind == SyntaxKind.OpenParenToken)
{
// Special case for crefs like "string()" and "A::B()".
CrefParameterListSyntax parameters = ParseCrefParameterList();
result = SyntaxFactory.NameMemberCref(type, parameters);
}
else
{
SyntaxToken dot = EatToken(SyntaxKind.DotToken);
MemberCrefSyntax member = ParseMemberCref();
result = SyntaxFactory.QualifiedCref(type, dot, member);
}
bool needOverallError = !IsEndOfCrefAttribute || result.ContainsDiagnostics;
if (!IsEndOfCrefAttribute)
{
var badTokens = _pool.Allocate<SyntaxToken>();
while (!IsEndOfCrefAttribute)
{
badTokens.Add(this.EatToken());
}
result = AddTrailingSkippedSyntax(result, badTokens.ToListNode());
_pool.Free(badTokens);
}
if (needOverallError)
{
result = this.AddError(result, ErrorCode.WRN_BadXMLRefSyntax, result.ToFullString());
}
return result;
}
/// <summary>
/// Parse the custom cref syntax for a named member (method, property, etc),
/// an indexer, an overloadable operator, or a user-defined conversion.
/// </summary>
private MemberCrefSyntax ParseMemberCref()
{
switch (CurrentToken.Kind)
{
case SyntaxKind.ThisKeyword:
return ParseIndexerMemberCref();
case SyntaxKind.OperatorKeyword:
return ParseOperatorMemberCref();
case SyntaxKind.ExplicitKeyword:
case SyntaxKind.ImplicitKeyword:
return ParseConversionOperatorMemberCref();
default:
return ParseNameMemberCref();
}
}
/// <summary>
/// Parse a named member (method, property, etc), with optional type
/// parameters and regular parameters.
/// </summary>
private NameMemberCrefSyntax ParseNameMemberCref()
{
SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers: true);
CrefParameterListSyntax parameters = ParseCrefParameterList();
return SyntaxFactory.NameMemberCref(name, parameters);
}
/// <summary>
/// Parse an indexer member, with optional parameters.
/// </summary>
private IndexerMemberCrefSyntax ParseIndexerMemberCref()
{
Debug.Assert(CurrentToken.Kind == SyntaxKind.ThisKeyword);
SyntaxToken thisKeyword = EatToken();
CrefBracketedParameterListSyntax parameters = ParseBracketedCrefParameterList();
return SyntaxFactory.IndexerMemberCref(thisKeyword, parameters);
}
/// <summary>
/// Parse an overloadable operator, with optional parameters.
/// </summary>
private OperatorMemberCrefSyntax ParseOperatorMemberCref()
{
Debug.Assert(CurrentToken.Kind == SyntaxKind.OperatorKeyword);
SyntaxToken operatorKeyword = EatToken();
SyntaxToken operatorToken;
if (SyntaxFacts.IsAnyOverloadableOperator(CurrentToken.Kind))
{
operatorToken = EatToken();
}
else
{
operatorToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken);
// Grab the offset and width before we consume the invalid keyword and change our position.
int offset;
int width;
GetDiagnosticSpanForMissingToken(out offset, out width);
if (SyntaxFacts.IsUnaryOperatorDeclarationToken(CurrentToken.Kind) || SyntaxFacts.IsBinaryExpressionOperatorToken(CurrentToken.Kind))
{
operatorToken = AddTrailingSkippedSyntax(operatorToken, EatToken());
}
SyntaxDiagnosticInfo rawInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected);
SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code);
operatorToken = WithAdditionalDiagnostics(operatorToken, crefInfo);
}
// Have to fake >> because it looks like the closing of nested type parameter lists (e.g. A<A<T>>).
// Have to fake >= so the lexer doesn't mishandle >>=.
if (operatorToken.Kind == SyntaxKind.GreaterThanToken && operatorToken.GetTrailingTriviaWidth() == 0 && CurrentToken.GetLeadingTriviaWidth() == 0)
{
if (CurrentToken.Kind == SyntaxKind.GreaterThanToken)
{
var operatorToken2 = this.EatToken();
operatorToken = SyntaxFactory.Token(
operatorToken.GetLeadingTrivia(),
SyntaxKind.GreaterThanGreaterThanToken,
operatorToken.Text + operatorToken2.Text,
operatorToken.ValueText + operatorToken2.ValueText,
operatorToken2.GetTrailingTrivia());
}
else if (CurrentToken.Kind == SyntaxKind.EqualsToken)
{
var operatorToken2 = this.EatToken();
operatorToken = SyntaxFactory.Token(
operatorToken.GetLeadingTrivia(),
SyntaxKind.GreaterThanEqualsToken,
operatorToken.Text + operatorToken2.Text,
operatorToken.ValueText + operatorToken2.ValueText,
operatorToken2.GetTrailingTrivia());
}
else if (CurrentToken.Kind == SyntaxKind.GreaterThanEqualsToken)
{
var operatorToken2 = this.EatToken();
var nonOverloadableOperator = SyntaxFactory.Token(
operatorToken.GetLeadingTrivia(),
SyntaxKind.GreaterThanGreaterThanEqualsToken,
operatorToken.Text + operatorToken2.Text,
operatorToken.ValueText + operatorToken2.ValueText,
operatorToken2.GetTrailingTrivia());
operatorToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken);
// Add non-overloadable operator as skipped token.
operatorToken = AddTrailingSkippedSyntax(operatorToken, nonOverloadableOperator);
// Add an appropriate diagnostic.
const int offset = 0;
int width = nonOverloadableOperator.Width;
SyntaxDiagnosticInfo rawInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected);
SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code);
operatorToken = WithAdditionalDiagnostics(operatorToken, crefInfo);
}
}
Debug.Assert(SyntaxFacts.IsAnyOverloadableOperator(operatorToken.Kind));
CrefParameterListSyntax parameters = ParseCrefParameterList();
return SyntaxFactory.OperatorMemberCref(operatorKeyword, operatorToken, parameters);
}
/// <summary>
/// Parse a user-defined conversion, with optional parameters.
/// </summary>
private ConversionOperatorMemberCrefSyntax ParseConversionOperatorMemberCref()
{
Debug.Assert(CurrentToken.Kind == SyntaxKind.ExplicitKeyword ||
CurrentToken.Kind == SyntaxKind.ImplicitKeyword);
SyntaxToken implicitOrExplicit = EatToken();
SyntaxToken operatorKeyword = EatToken(SyntaxKind.OperatorKeyword);
TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false);
CrefParameterListSyntax parameters = ParseCrefParameterList();
return SyntaxFactory.ConversionOperatorMemberCref(implicitOrExplicit, operatorKeyword, type, parameters);
}
/// <summary>
/// Parse a parenthesized parameter list.
/// </summary>
private CrefParameterListSyntax ParseCrefParameterList()
{
return (CrefParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: false);
}
/// <summary>
/// Parse a bracketed parameter list.
/// </summary>
private CrefBracketedParameterListSyntax ParseBracketedCrefParameterList()
{
return (CrefBracketedParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: true);
}
/// <summary>
/// Parse the parameter list (if any) of a cref member (name, indexer, operator, or conversion).
/// </summary>
private BaseCrefParameterListSyntax ParseBaseCrefParameterList(bool useSquareBrackets)
{
SyntaxKind openKind = useSquareBrackets ? SyntaxKind.OpenBracketToken : SyntaxKind.OpenParenToken;
SyntaxKind closeKind = useSquareBrackets ? SyntaxKind.CloseBracketToken : SyntaxKind.CloseParenToken;
if (CurrentToken.Kind != openKind)
{
return null;
}
SyntaxToken open = EatToken(openKind);
var list = _pool.AllocateSeparated<CrefParameterSyntax>();
try
{
while (CurrentToken.Kind == SyntaxKind.CommaToken || IsPossibleCrefParameter())
{
list.Add(ParseCrefParameter());
if (CurrentToken.Kind != closeKind)
{
SyntaxToken comma = EatToken(SyntaxKind.CommaToken);
if (!comma.IsMissing || IsPossibleCrefParameter())
{
// Only do this if it won't be last in the list.
list.AddSeparator(comma);
}
else
{
// How could this scenario arise? If it does, just expand the if-condition.
Debug.Assert(CurrentToken.Kind != SyntaxKind.CommaToken);
}
}
}
// NOTE: nothing follows a cref parameter list, so there's no reason to recover here.
// Just let the cref-level recovery code handle any remaining tokens.
SyntaxToken close = EatToken(closeKind);
return useSquareBrackets
? (BaseCrefParameterListSyntax)SyntaxFactory.CrefBracketedParameterList(open, list, close)
: SyntaxFactory.CrefParameterList(open, list, close);
}
finally
{
_pool.Free(list);
}
}
/// <summary>
/// True if the current token could be the beginning of a cref parameter.
/// </summary>
private bool IsPossibleCrefParameter()
{
SyntaxKind kind = this.CurrentToken.Kind;
switch (kind)
{
case SyntaxKind.RefKeyword:
case SyntaxKind.OutKeyword:
case SyntaxKind.InKeyword:
case SyntaxKind.IdentifierToken:
return true;
default:
return SyntaxFacts.IsPredefinedType(kind);
}
}
/// <summary>
/// Parse an element of a cref parameter list.
/// </summary>
/// <remarks>
/// "ref" and "out" work, but "params", "this", and "__arglist" don't.
/// </remarks>
private CrefParameterSyntax ParseCrefParameter()
{
SyntaxToken refKindOpt = null;
switch (CurrentToken.Kind)
{
case SyntaxKind.RefKeyword:
case SyntaxKind.OutKeyword:
case SyntaxKind.InKeyword:
refKindOpt = EatToken();
break;
}
TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false);
return SyntaxFactory.CrefParameter(refKindOpt, type);
}
/// <summary>
/// Parse an identifier, optionally followed by an angle-bracketed list of type parameters.
/// </summary>
/// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier
/// type argument is seen, false to accept. No change in the shape of the tree.</param>
private SimpleNameSyntax ParseCrefName(bool typeArgumentsMustBeIdentifiers)
{
SyntaxToken identifierToken = EatToken(SyntaxKind.IdentifierToken);
if (CurrentToken.Kind != SyntaxKind.LessThanToken)
{
return SyntaxFactory.IdentifierName(identifierToken);
}
var open = EatToken();
var list = _pool.AllocateSeparated<TypeSyntax>();
try
{
while (true)
{
TypeSyntax typeSyntax = ParseCrefType(typeArgumentsMustBeIdentifiers);
if (typeArgumentsMustBeIdentifiers && typeSyntax.Kind != SyntaxKind.IdentifierName)
{
typeSyntax = this.AddError(typeSyntax, ErrorCode.WRN_ErrorOverride,
new SyntaxDiagnosticInfo(ErrorCode.ERR_TypeParamMustBeIdentifier), $"{(int)ErrorCode.ERR_TypeParamMustBeIdentifier:d4}");
}
list.Add(typeSyntax);
var currentKind = CurrentToken.Kind;
if (currentKind == SyntaxKind.CommaToken || currentKind == SyntaxKind.IdentifierToken ||
SyntaxFacts.IsPredefinedType(CurrentToken.Kind))
{
// NOTE: if the current token is an identifier or predefined type, then we're
// actually inserting a missing commas.
list.AddSeparator(EatToken(SyntaxKind.CommaToken));
}
else
{
break;
}
}
SyntaxToken close = EatToken(SyntaxKind.GreaterThanToken);
open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics, forceWarning: true);
return SyntaxFactory.GenericName(identifierToken, SyntaxFactory.TypeArgumentList(open, list, close));
}
finally
{
_pool.Free(list);
}
}
/// <summary>
/// Parse a type. May include an alias, a predefined type, and/or a qualified name.
/// </summary>
/// <remarks>
/// Pointer, nullable, or array types are only allowed if <paramref name="typeArgumentsMustBeIdentifiers"/> is false.
/// Leaves a dot and a name unconsumed if the name is not followed by another dot
/// and checkForMember is true.
/// </remarks>
/// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier
/// type argument is seen, false to accept. No change in the shape of the tree.</param>
/// <param name="checkForMember">True means that the last name should not be consumed
/// if it is followed by a parameter list.</param>
private TypeSyntax ParseCrefType(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false)
{
TypeSyntax typeWithoutSuffix = ParseCrefTypeHelper(typeArgumentsMustBeIdentifiers, checkForMember);
return typeArgumentsMustBeIdentifiers
? typeWithoutSuffix
: ParseCrefTypeSuffix(typeWithoutSuffix);
}
/// <summary>
/// Parse a type. May include an alias, a predefined type, and/or a qualified name.
/// </summary>
/// <remarks>
/// No pointer, nullable, or array types.
/// Leaves a dot and a name unconsumed if the name is not followed by another dot
/// and checkForMember is true.
/// </remarks>
/// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier
/// type argument is seen, false to accept. No change in the shape of the tree.</param>
/// <param name="checkForMember">True means that the last name should not be consumed
/// if it is followed by a parameter list.</param>
private TypeSyntax ParseCrefTypeHelper(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false)
{
NameSyntax leftName;
if (SyntaxFacts.IsPredefinedType(CurrentToken.Kind))
{
// e.g. "int"
// NOTE: a predefined type will not fit into a NameSyntax, so we'll return
// immediately. The upshot is that you can only dot into a predefined type
// once (e.g. not "int.A.B"), which is fine because we know that none of them
// have nested types.
return SyntaxFactory.PredefinedType(EatToken());
}
else if (CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.ColonColonToken)
{
// e.g. "A::B"
SyntaxToken alias = EatToken();
if (alias.ContextualKind == SyntaxKind.GlobalKeyword)
{
alias = ConvertToKeyword(alias);
}
alias = CheckFeatureAvailability(alias, MessageID.IDS_FeatureGlobalNamespace, forceWarning: true);
SyntaxToken colonColon = EatToken();
SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers);
leftName = SyntaxFactory.AliasQualifiedName(SyntaxFactory.IdentifierName(alias), colonColon, name);
}
else
{
// e.g. "A"
ResetPoint resetPoint = GetResetPoint();
leftName = ParseCrefName(typeArgumentsMustBeIdentifiers);
if (checkForMember && (leftName.IsMissing || CurrentToken.Kind != SyntaxKind.DotToken))
{
// If this isn't the first part of a dotted name, then we prefer to represent it
// as a MemberCrefSyntax.
this.Reset(ref resetPoint);
this.Release(ref resetPoint);
return null;
}
this.Release(ref resetPoint);
}
while (CurrentToken.Kind == SyntaxKind.DotToken)
{
// NOTE: we make a lot of these, but we'll reset, at most, one time.
ResetPoint resetPoint = GetResetPoint();
SyntaxToken dot = EatToken();
SimpleNameSyntax rightName = ParseCrefName(typeArgumentsMustBeIdentifiers);
if (checkForMember && (rightName.IsMissing || CurrentToken.Kind != SyntaxKind.DotToken))
{
this.Reset(ref resetPoint); // Go back to before the dot - it must have been the trailing dot.
this.Release(ref resetPoint);
return leftName;
}
this.Release(ref resetPoint);
leftName = SyntaxFactory.QualifiedName(leftName, dot, rightName);
}
return leftName;
}
/// <summary>
/// Once the name part of a type (including type parameter/argument lists) is parsed,
/// we need to consume ?, *, and rank specifiers.
/// </summary>
private TypeSyntax ParseCrefTypeSuffix(TypeSyntax type)
{
if (CurrentToken.Kind == SyntaxKind.QuestionToken)
{
type = SyntaxFactory.NullableType(type, EatToken());
}
while (CurrentToken.Kind == SyntaxKind.AsteriskToken)
{
type = SyntaxFactory.PointerType(type, EatToken());
}
if (CurrentToken.Kind == SyntaxKind.OpenBracketToken)
{
var omittedArraySizeExpressionInstance = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken));
var rankList = _pool.Allocate<ArrayRankSpecifierSyntax>();
try
{
while (CurrentToken.Kind == SyntaxKind.OpenBracketToken)
{
SyntaxToken open = EatToken();
var dimensionList = _pool.AllocateSeparated<ExpressionSyntax>();
try
{
while (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken)
{
if (this.CurrentToken.Kind == SyntaxKind.CommaToken)
{
// NOTE: trivia will be attached to comma, not omitted array size
dimensionList.Add(omittedArraySizeExpressionInstance);
dimensionList.AddSeparator(this.EatToken());
}
else
{
// CONSIDER: if we expect people to try to put expressions in between
// the commas, then it might be more reasonable to recover by skipping
// tokens until we hit a CloseBracketToken (or some other terminator).
break;
}
}
// Don't end on a comma.
// If the omitted size would be the only element, then skip it unless sizes were expected.
if ((dimensionList.Count & 1) == 0)
{
dimensionList.Add(omittedArraySizeExpressionInstance);
}
// Eat the close brace and we're done.
var close = this.EatToken(SyntaxKind.CloseBracketToken);
rankList.Add(SyntaxFactory.ArrayRankSpecifier(open, dimensionList, close));
}
finally
{
_pool.Free(dimensionList);
}
}
type = SyntaxFactory.ArrayType(type, rankList);
}
finally
{
_pool.Free(rankList);
}
}
return type;
}
/// <summary>
/// Ends at appropriate quotation mark, EOF, or EndOfDocumentationComment.
/// </summary>
private bool IsEndOfCrefAttribute
{
get
{
switch (CurrentToken.Kind)
{
case SyntaxKind.SingleQuoteToken:
return (this.Mode & LexerMode.XmlCrefQuote) == LexerMode.XmlCrefQuote;
case SyntaxKind.DoubleQuoteToken:
return (this.Mode & LexerMode.XmlCrefDoubleQuote) == LexerMode.XmlCrefDoubleQuote;
case SyntaxKind.EndOfFileToken:
case SyntaxKind.EndOfDocumentationCommentToken:
return true;
case SyntaxKind.BadToken:
// If it's a real '<' (not <, etc), then we assume it's the beginning
// of the next XML element.
return CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken) ||
IsNonAsciiQuotationMark(CurrentToken);
default:
return false;
}
}
}
/// <summary>
/// Convenience method for checking the mode.
/// </summary>
private bool InCref
{
get
{
switch (this.Mode & (LexerMode.XmlCrefDoubleQuote | LexerMode.XmlCrefQuote))
{
case LexerMode.XmlCrefQuote:
case LexerMode.XmlCrefDoubleQuote:
return true;
default:
return false;
}
}
}
#endregion Cref
#region Name attribute values
private IdentifierNameSyntax ParseNameAttributeValue()
{
// Never report a parse error - just fail to bind the name later on.
SyntaxToken identifierToken = this.EatToken(SyntaxKind.IdentifierToken, reportError: false);
if (!IsEndOfNameAttribute)
{
var badTokens = _pool.Allocate<SyntaxToken>();
while (!IsEndOfNameAttribute)
{
badTokens.Add(this.EatToken());
}
identifierToken = AddTrailingSkippedSyntax(identifierToken, badTokens.ToListNode());
_pool.Free(badTokens);
}
return SyntaxFactory.IdentifierName(identifierToken);
}
/// <summary>
/// Ends at appropriate quotation mark, EOF, or EndOfDocumentationComment.
/// </summary>
private bool IsEndOfNameAttribute
{
get
{
switch (CurrentToken.Kind)
{
case SyntaxKind.SingleQuoteToken:
return (this.Mode & LexerMode.XmlNameQuote) == LexerMode.XmlNameQuote;
case SyntaxKind.DoubleQuoteToken:
return (this.Mode & LexerMode.XmlNameDoubleQuote) == LexerMode.XmlNameDoubleQuote;
case SyntaxKind.EndOfFileToken:
case SyntaxKind.EndOfDocumentationCommentToken:
return true;
case SyntaxKind.BadToken:
// If it's a real '<' (not <, etc), then we assume it's the beginning
// of the next XML element.
return CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken) ||
IsNonAsciiQuotationMark(CurrentToken);
default:
return false;
}
}
}
#endregion Name attribute values
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
// TODO: The Xml parser recognizes most commonplace XML, according to the XML spec.
// It does not recognize the following:
//
// * Document Type Definition
// <!DOCTYPE ... >
// * Element Type Declaration, Attribute-List Declarations, Entity Declarations, Notation Declarations
// <!ELEMENT ... >
// <!ATTLIST ... >
// <!ENTITY ... >
// <!NOTATION ... >
// * Conditional Sections
// <![INCLUDE[ ... ]]>
// <![IGNORE[ ... ]]>
//
// This probably does not matter. However, if it becomes necessary to recognize any
// of these bits of XML, the most sensible thing to do is probably to scan them without
// trying to understand them, e.g. like comments or CDATA, so that they are available
// to whoever processes these comments and do not produce an error.
internal class DocumentationCommentParser : SyntaxParser
{
private readonly SyntaxListPool _pool = new SyntaxListPool();
private bool _isDelimited;
internal DocumentationCommentParser(Lexer lexer, LexerMode modeflags)
: base(lexer, LexerMode.XmlDocComment | LexerMode.XmlDocCommentLocationStart | modeflags, null, null, true)
{
_isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0;
}
internal void ReInitialize(LexerMode modeflags)
{
base.ReInitialize();
this.Mode = LexerMode.XmlDocComment | LexerMode.XmlDocCommentLocationStart | modeflags;
_isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0;
}
private LexerMode SetMode(LexerMode mode)
{
var tmp = this.Mode;
this.Mode = mode | (tmp & (LexerMode.MaskXmlDocCommentLocation | LexerMode.MaskXmlDocCommentStyle));
return tmp;
}
private void ResetMode(LexerMode mode)
{
this.Mode = mode;
}
public DocumentationCommentTriviaSyntax ParseDocumentationComment(out bool isTerminated)
{
var nodes = _pool.Allocate<XmlNodeSyntax>();
try
{
this.ParseXmlNodes(nodes);
// It's possible that we finish parsing the xml, and we are still left in the middle
// of an Xml comment. For example,
//
// /// <goo></goo></uhoh>
// ^
// In this case, we stop at the caret. We need to ensure that we consume the remainder
// of the doc comment here, since otherwise we will return the lexer to the state
// where it recognizes C# tokens, which means that C# parser will get the </uhoh>,
// which is not at all what we want.
if (this.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken)
{
this.ParseRemainder(nodes);
}
var eoc = this.EatToken(SyntaxKind.EndOfDocumentationCommentToken);
isTerminated = !_isDelimited || (eoc.LeadingTrivia.Count > 0 && eoc.LeadingTrivia[eoc.LeadingTrivia.Count - 1].ToString() == "*/");
SyntaxKind kind = _isDelimited ? SyntaxKind.MultiLineDocumentationCommentTrivia : SyntaxKind.SingleLineDocumentationCommentTrivia;
return SyntaxFactory.DocumentationCommentTrivia(kind, nodes.ToList(), eoc);
}
finally
{
_pool.Free(nodes);
}
}
public void ParseRemainder(SyntaxListBuilder<XmlNodeSyntax> nodes)
{
bool endTag = this.CurrentToken.Kind == SyntaxKind.LessThanSlashToken;
var saveMode = this.SetMode(LexerMode.XmlCDataSectionText);
var textTokens = _pool.Allocate();
try
{
while (this.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken)
{
var token = this.EatToken();
// TODO: It is possible that a non-literal gets in here. ]]>, specifically. Is that ok?
textTokens.Add(token);
}
var allRemainderText = SyntaxFactory.XmlText(textTokens.ToList());
XmlParseErrorCode code = endTag ? XmlParseErrorCode.XML_EndTagNotExpected : XmlParseErrorCode.XML_ExpectedEndOfXml;
allRemainderText = WithAdditionalDiagnostics(allRemainderText, new XmlSyntaxDiagnosticInfo(0, 1, code));
nodes.Add(allRemainderText);
}
finally
{
_pool.Free(textTokens);
}
this.ResetMode(saveMode);
}
private void ParseXmlNodes(SyntaxListBuilder<XmlNodeSyntax> nodes)
{
while (true)
{
var node = this.ParseXmlNode();
if (node == null)
{
return;
}
nodes.Add(node);
}
}
private XmlNodeSyntax ParseXmlNode()
{
switch (this.CurrentToken.Kind)
{
case SyntaxKind.XmlTextLiteralToken:
case SyntaxKind.XmlTextLiteralNewLineToken:
case SyntaxKind.XmlEntityLiteralToken:
return this.ParseXmlText();
case SyntaxKind.LessThanToken:
return this.ParseXmlElement();
case SyntaxKind.XmlCommentStartToken:
return this.ParseXmlComment();
case SyntaxKind.XmlCDataStartToken:
return this.ParseXmlCDataSection();
case SyntaxKind.XmlProcessingInstructionStartToken:
return this.ParseXmlProcessingInstruction();
case SyntaxKind.EndOfDocumentationCommentToken:
return null;
default:
// This means we have some unrecognized token. We probably need to give an error.
return null;
}
}
private bool IsXmlNodeStartOrStop()
{
switch (this.CurrentToken.Kind)
{
case SyntaxKind.LessThanToken:
case SyntaxKind.LessThanSlashToken:
case SyntaxKind.XmlCommentStartToken:
case SyntaxKind.XmlCDataStartToken:
case SyntaxKind.XmlProcessingInstructionStartToken:
case SyntaxKind.GreaterThanToken:
case SyntaxKind.SlashGreaterThanToken:
case SyntaxKind.EndOfDocumentationCommentToken:
return true;
default:
return false;
}
}
private XmlNodeSyntax ParseXmlText()
{
var textTokens = _pool.Allocate();
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken
|| this.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken)
{
textTokens.Add(this.EatToken());
}
var list = textTokens.ToList();
_pool.Free(textTokens);
return SyntaxFactory.XmlText(list);
}
private XmlNodeSyntax ParseXmlElement()
{
var lessThan = this.EatToken(SyntaxKind.LessThanToken); // guaranteed
var saveMode = this.SetMode(LexerMode.XmlElementTag);
var name = this.ParseXmlName();
if (lessThan.GetTrailingTriviaWidth() > 0 || name.GetLeadingTriviaWidth() > 0)
{
// The Xml spec disallows whitespace here: STag ::= '<' Name (S Attribute)* S? '>'
name = this.WithXmlParseError(name, XmlParseErrorCode.XML_InvalidWhitespace);
}
var attrs = _pool.Allocate<XmlAttributeSyntax>();
try
{
this.ParseXmlAttributes(ref name, attrs);
if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken)
{
var startTag = SyntaxFactory.XmlElementStartTag(lessThan, name, attrs, this.EatToken());
this.SetMode(LexerMode.XmlDocComment);
var nodes = _pool.Allocate<XmlNodeSyntax>();
try
{
this.ParseXmlNodes(nodes);
XmlNameSyntax endName;
SyntaxToken greaterThan;
// end tag
var lessThanSlash = this.EatToken(SyntaxKind.LessThanSlashToken, reportError: false);
// If we didn't see "</", then we can't really be confident that this is actually an end tag,
// so just insert a missing one.
if (lessThanSlash.IsMissing)
{
this.ResetMode(saveMode);
lessThanSlash = this.WithXmlParseError(lessThanSlash, XmlParseErrorCode.XML_EndTagExpected, name.ToString());
endName = SyntaxFactory.XmlName(prefix: null, localName: SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
greaterThan = SyntaxFactory.MissingToken(SyntaxKind.GreaterThanToken);
}
else
{
this.SetMode(LexerMode.XmlElementTag);
endName = this.ParseXmlName();
if (lessThanSlash.GetTrailingTriviaWidth() > 0 || endName.GetLeadingTriviaWidth() > 0)
{
// The Xml spec disallows whitespace here: STag ::= '<' Name (S Attribute)* S? '>'
endName = this.WithXmlParseError(endName, XmlParseErrorCode.XML_InvalidWhitespace);
}
if (!endName.IsMissing && !MatchingXmlNames(name, endName))
{
endName = this.WithXmlParseError(endName, XmlParseErrorCode.XML_ElementTypeMatch, endName.ToString(), name.ToString());
}
// if we don't see the greater than token then skip the badness until we do or abort
if (this.CurrentToken.Kind != SyntaxKind.GreaterThanToken)
{
this.SkipBadTokens(ref endName, null,
p => p.CurrentToken.Kind != SyntaxKind.GreaterThanToken,
p => p.IsXmlNodeStartOrStop(),
XmlParseErrorCode.XML_InvalidToken
);
}
greaterThan = this.EatToken(SyntaxKind.GreaterThanToken);
}
var endTag = SyntaxFactory.XmlElementEndTag(lessThanSlash, endName, greaterThan);
this.ResetMode(saveMode);
return SyntaxFactory.XmlElement(startTag, nodes.ToList(), endTag);
}
finally
{
_pool.Free(nodes);
}
}
else
{
var slashGreater = this.EatToken(SyntaxKind.SlashGreaterThanToken, false);
if (slashGreater.IsMissing && !name.IsMissing)
{
slashGreater = this.WithXmlParseError(slashGreater, XmlParseErrorCode.XML_ExpectedEndOfTag, name.ToString());
}
this.ResetMode(saveMode);
return SyntaxFactory.XmlEmptyElement(lessThan, name, attrs, slashGreater);
}
}
finally
{
_pool.Free(attrs);
}
}
private static bool MatchingXmlNames(XmlNameSyntax name, XmlNameSyntax endName)
{
// PERF: because of deduplication we often get the same name for name and endName,
// so we will check for such case first before materializing text for entire nodes
// and comparing that.
if (name == endName)
{
return true;
}
// before doing ToString, check if
// all nodes contributing to ToString are recursively the same
// NOTE: leading and trailing trivia do not contribute to ToString
if (!name.HasLeadingTrivia &&
!endName.HasTrailingTrivia &&
name.IsEquivalentTo(endName))
{
return true;
}
return name.ToString() == endName.ToString();
}
// assuming this is not used concurrently
private readonly HashSet<string> _attributesSeen = new HashSet<string>();
private void ParseXmlAttributes(ref XmlNameSyntax elementName, SyntaxListBuilder<XmlAttributeSyntax> attrs)
{
_attributesSeen.Clear();
while (true)
{
if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken)
{
var attr = this.ParseXmlAttribute(elementName);
string attrName = attr.Name.ToString();
if (_attributesSeen.Contains(attrName))
{
attr = this.WithXmlParseError(attr, XmlParseErrorCode.XML_DuplicateAttribute, attrName);
}
else
{
_attributesSeen.Add(attrName);
}
attrs.Add(attr);
}
else
{
var skip = this.SkipBadTokens(ref elementName, attrs,
// not expected condition
p => p.CurrentToken.Kind != SyntaxKind.IdentifierName,
// abort condition (looks like something we might understand later)
p => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken
|| p.CurrentToken.Kind == SyntaxKind.SlashGreaterThanToken
|| p.CurrentToken.Kind == SyntaxKind.LessThanToken
|| p.CurrentToken.Kind == SyntaxKind.LessThanSlashToken
|| p.CurrentToken.Kind == SyntaxKind.EndOfDocumentationCommentToken
|| p.CurrentToken.Kind == SyntaxKind.EndOfFileToken,
XmlParseErrorCode.XML_InvalidToken
);
if (skip == SkipResult.Abort)
{
break;
}
}
}
}
private enum SkipResult
{
Continue,
Abort
}
private SkipResult SkipBadTokens<T>(
ref T startNode,
SyntaxListBuilder list,
Func<DocumentationCommentParser, bool> isNotExpectedFunction,
Func<DocumentationCommentParser, bool> abortFunction,
XmlParseErrorCode error
) where T : CSharpSyntaxNode
{
var badTokens = default(SyntaxListBuilder<SyntaxToken>);
bool hasError = false;
try
{
SkipResult result = SkipResult.Continue;
while (isNotExpectedFunction(this))
{
if (abortFunction(this))
{
result = SkipResult.Abort;
break;
}
if (badTokens.IsNull)
{
badTokens = _pool.Allocate<SyntaxToken>();
}
var token = this.EatToken();
if (!hasError)
{
token = this.WithXmlParseError(token, error, token.ToString());
hasError = true;
}
badTokens.Add(token);
}
if (!badTokens.IsNull && badTokens.Count > 0)
{
// use skipped text since cannot nest structured trivia under structured trivia
if (list == null || list.Count == 0)
{
startNode = AddTrailingSkippedSyntax(startNode, badTokens.ToListNode());
}
else
{
list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], badTokens.ToListNode());
}
return result;
}
else
{
// somehow we did not consume anything, so tell caller to abort parse rule
return SkipResult.Abort;
}
}
finally
{
if (!badTokens.IsNull)
{
_pool.Free(badTokens);
}
}
}
private XmlAttributeSyntax ParseXmlAttribute(XmlNameSyntax elementName)
{
var attrName = this.ParseXmlName();
if (attrName.GetLeadingTriviaWidth() == 0)
{
// The Xml spec requires whitespace here: STag ::= '<' Name (S Attribute)* S? '>'
attrName = this.WithXmlParseError(attrName, XmlParseErrorCode.XML_WhitespaceMissing);
}
var equals = this.EatToken(SyntaxKind.EqualsToken, false);
if (equals.IsMissing)
{
equals = this.WithXmlParseError(equals, XmlParseErrorCode.XML_MissingEqualsAttribute);
switch (this.CurrentToken.Kind)
{
case SyntaxKind.SingleQuoteToken:
case SyntaxKind.DoubleQuoteToken:
// There could be a value coming up, let's keep parsing.
break;
default:
// This is probably not a complete attribute.
return SyntaxFactory.XmlTextAttribute(
attrName,
equals,
SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken),
default(SyntaxList<SyntaxToken>),
SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken));
}
}
SyntaxToken startQuote;
SyntaxToken endQuote;
string attrNameText = attrName.LocalName.ValueText;
bool hasNoPrefix = attrName.Prefix == null;
if (hasNoPrefix && DocumentationCommentXmlNames.AttributeEquals(attrNameText, DocumentationCommentXmlNames.CrefAttributeName) &&
!IsVerbatimCref())
{
CrefSyntax cref;
this.ParseCrefAttribute(out startQuote, out cref, out endQuote);
return SyntaxFactory.XmlCrefAttribute(attrName, equals, startQuote, cref, endQuote);
}
else if (hasNoPrefix && DocumentationCommentXmlNames.AttributeEquals(attrNameText, DocumentationCommentXmlNames.NameAttributeName) &&
XmlElementSupportsNameAttribute(elementName))
{
IdentifierNameSyntax identifier;
this.ParseNameAttribute(out startQuote, out identifier, out endQuote);
return SyntaxFactory.XmlNameAttribute(attrName, equals, startQuote, identifier, endQuote);
}
else
{
var textTokens = _pool.Allocate<SyntaxToken>();
try
{
this.ParseXmlAttributeText(out startQuote, textTokens, out endQuote);
return SyntaxFactory.XmlTextAttribute(attrName, equals, startQuote, textTokens, endQuote);
}
finally
{
_pool.Free(textTokens);
}
}
}
private static bool XmlElementSupportsNameAttribute(XmlNameSyntax elementName)
{
if (elementName.Prefix != null)
{
return false;
}
string localName = elementName.LocalName.ValueText;
return
DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.ParameterElementName) ||
DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.ParameterReferenceElementName) ||
DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.TypeParameterElementName) ||
DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.TypeParameterReferenceElementName);
}
private bool IsVerbatimCref()
{
// As in XMLDocWriter::ReplaceReferences, if the first character of the value is not colon and the second character
// is, then don't process the cref - just emit it as-is.
bool isVerbatim = false;
var resetPoint = this.GetResetPoint();
SyntaxToken openQuote = EatToken(this.CurrentToken.Kind == SyntaxKind.SingleQuoteToken
? SyntaxKind.SingleQuoteToken
: SyntaxKind.DoubleQuoteToken);
// NOTE: Don't need to save mode, since we're already using a reset point.
this.SetMode(LexerMode.XmlCharacter);
SyntaxToken current = this.CurrentToken;
if ((current.Kind == SyntaxKind.XmlTextLiteralToken || current.Kind == SyntaxKind.XmlEntityLiteralToken) &&
current.ValueText != SyntaxFacts.GetText(openQuote.Kind) &&
current.ValueText != ":")
{
EatToken();
current = this.CurrentToken;
if ((current.Kind == SyntaxKind.XmlTextLiteralToken || current.Kind == SyntaxKind.XmlEntityLiteralToken) &&
current.ValueText == ":")
{
isVerbatim = true;
}
}
this.Reset(ref resetPoint);
this.Release(ref resetPoint);
return isVerbatim;
}
private void ParseCrefAttribute(out SyntaxToken startQuote, out CrefSyntax cref, out SyntaxToken endQuote)
{
startQuote = ParseXmlAttributeStartQuote();
SyntaxKind quoteKind = startQuote.Kind;
{
var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken
? LexerMode.XmlCrefQuote
: LexerMode.XmlCrefDoubleQuote);
cref = this.ParseCrefAttributeValue();
this.ResetMode(saveMode);
}
endQuote = ParseXmlAttributeEndQuote(quoteKind);
}
private void ParseNameAttribute(out SyntaxToken startQuote, out IdentifierNameSyntax identifier, out SyntaxToken endQuote)
{
startQuote = ParseXmlAttributeStartQuote();
SyntaxKind quoteKind = startQuote.Kind;
{
var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken
? LexerMode.XmlNameQuote
: LexerMode.XmlNameDoubleQuote);
identifier = this.ParseNameAttributeValue();
this.ResetMode(saveMode);
}
endQuote = ParseXmlAttributeEndQuote(quoteKind);
}
private void ParseXmlAttributeText(out SyntaxToken startQuote, SyntaxListBuilder<SyntaxToken> textTokens, out SyntaxToken endQuote)
{
startQuote = ParseXmlAttributeStartQuote();
SyntaxKind quoteKind = startQuote.Kind;
// NOTE: Being a bit sneaky here - if the width isn't 0, we consumed something else in
// place of the quote and we should continue parsing the attribute.
if (startQuote.IsMissing && startQuote.FullWidth == 0)
{
endQuote = SyntaxFactory.MissingToken(quoteKind);
}
else
{
var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken
? LexerMode.XmlAttributeTextQuote
: LexerMode.XmlAttributeTextDoubleQuote);
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken
|| this.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.LessThanToken)
{
var token = this.EatToken();
if (token.Kind == SyntaxKind.LessThanToken)
{
// TODO: It is possible that a non-literal gets in here. <, specifically. Is that ok?
token = this.WithXmlParseError(token, XmlParseErrorCode.XML_LessThanInAttributeValue);
}
textTokens.Add(token);
}
this.ResetMode(saveMode);
// NOTE: This will never consume a non-ascii quote, since non-ascii quotes
// are legal in the attribute value and are consumed by the preceding loop.
endQuote = ParseXmlAttributeEndQuote(quoteKind);
}
}
private SyntaxToken ParseXmlAttributeStartQuote()
{
if (IsNonAsciiQuotationMark(this.CurrentToken))
{
return SkipNonAsciiQuotationMark();
}
var quoteKind = this.CurrentToken.Kind == SyntaxKind.SingleQuoteToken
? SyntaxKind.SingleQuoteToken
: SyntaxKind.DoubleQuoteToken;
var startQuote = this.EatToken(quoteKind, reportError: false);
if (startQuote.IsMissing)
{
startQuote = this.WithXmlParseError(startQuote, XmlParseErrorCode.XML_StringLiteralNoStartQuote);
}
return startQuote;
}
private SyntaxToken ParseXmlAttributeEndQuote(SyntaxKind quoteKind)
{
if (IsNonAsciiQuotationMark(this.CurrentToken))
{
return SkipNonAsciiQuotationMark();
}
var endQuote = this.EatToken(quoteKind, reportError: false);
if (endQuote.IsMissing)
{
endQuote = this.WithXmlParseError(endQuote, XmlParseErrorCode.XML_StringLiteralNoEndQuote);
}
return endQuote;
}
private SyntaxToken SkipNonAsciiQuotationMark()
{
var quote = SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken);
quote = AddTrailingSkippedSyntax(quote, EatToken());
quote = this.WithXmlParseError(quote, XmlParseErrorCode.XML_StringLiteralNonAsciiQuote);
return quote;
}
/// <summary>
/// These aren't acceptable in place of ASCII quotation marks in XML,
/// but we want to consume them (and produce an appropriate error) if
/// they occur in a place where a quotation mark is legal.
/// </summary>
private static bool IsNonAsciiQuotationMark(SyntaxToken token)
{
return token.Text.Length == 1 && SyntaxFacts.IsNonAsciiQuotationMark(token.Text[0]);
}
private XmlNameSyntax ParseXmlName()
{
var id = this.EatToken(SyntaxKind.IdentifierToken);
XmlPrefixSyntax prefix = null;
if (this.CurrentToken.Kind == SyntaxKind.ColonToken)
{
var colon = this.EatToken();
int prefixTrailingWidth = id.GetTrailingTriviaWidth();
int colonLeadingWidth = colon.GetLeadingTriviaWidth();
if (prefixTrailingWidth > 0 || colonLeadingWidth > 0)
{
// NOTE: offset is relative to full-span start of colon (i.e. before leading trivia).
int offset = -prefixTrailingWidth;
int width = prefixTrailingWidth + colonLeadingWidth;
colon = WithAdditionalDiagnostics(colon, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace));
}
prefix = SyntaxFactory.XmlPrefix(id, colon);
id = this.EatToken(SyntaxKind.IdentifierToken);
int colonTrailingWidth = colon.GetTrailingTriviaWidth();
int localNameLeadingWidth = id.GetLeadingTriviaWidth();
if (colonTrailingWidth > 0 || localNameLeadingWidth > 0)
{
// NOTE: offset is relative to full-span start of identifier (i.e. before leading trivia).
int offset = -colonTrailingWidth;
int width = colonTrailingWidth + localNameLeadingWidth;
id = WithAdditionalDiagnostics(id, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace));
// CONSIDER: Another interpretation would be that the local part of this name is a missing identifier and the identifier
// we've just consumed is actually part of something else (e.g. an attribute name).
}
}
return SyntaxFactory.XmlName(prefix, id);
}
private XmlCommentSyntax ParseXmlComment()
{
var lessThanExclamationMinusMinusToken = this.EatToken(SyntaxKind.XmlCommentStartToken);
var saveMode = this.SetMode(LexerMode.XmlCommentText);
var textTokens = _pool.Allocate<SyntaxToken>();
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken
|| this.CurrentToken.Kind == SyntaxKind.MinusMinusToken)
{
var token = this.EatToken();
if (token.Kind == SyntaxKind.MinusMinusToken)
{
// TODO: It is possible that a non-literal gets in here. --, specifically. Is that ok?
token = this.WithXmlParseError(token, XmlParseErrorCode.XML_IncorrectComment);
}
textTokens.Add(token);
}
var list = textTokens.ToList();
_pool.Free(textTokens);
var minusMinusGreaterThanToken = this.EatToken(SyntaxKind.XmlCommentEndToken);
this.ResetMode(saveMode);
return SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, list, minusMinusGreaterThanToken);
}
private XmlCDataSectionSyntax ParseXmlCDataSection()
{
var startCDataToken = this.EatToken(SyntaxKind.XmlCDataStartToken);
var saveMode = this.SetMode(LexerMode.XmlCDataSectionText);
var textTokens = new SyntaxListBuilder<SyntaxToken>(10);
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken)
{
textTokens.Add(this.EatToken());
}
var endCDataToken = this.EatToken(SyntaxKind.XmlCDataEndToken);
this.ResetMode(saveMode);
return SyntaxFactory.XmlCDataSection(startCDataToken, textTokens, endCDataToken);
}
private XmlProcessingInstructionSyntax ParseXmlProcessingInstruction()
{
var startProcessingInstructionToken = this.EatToken(SyntaxKind.XmlProcessingInstructionStartToken);
var saveMode = this.SetMode(LexerMode.XmlElementTag); //this mode accepts names
var name = this.ParseXmlName();
// NOTE: The XML spec says that name cannot be "xml" (case-insensitive comparison),
// but Dev10 does not enforce this.
this.SetMode(LexerMode.XmlProcessingInstructionText); //this mode consumes text
var textTokens = new SyntaxListBuilder<SyntaxToken>(10);
while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken
|| this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken)
{
var textToken = this.EatToken();
// NOTE: The XML spec says that the each text token must begin with a whitespace
// character, but Dev10 does not enforce this.
textTokens.Add(textToken);
}
var endProcessingInstructionToken = this.EatToken(SyntaxKind.XmlProcessingInstructionEndToken);
this.ResetMode(saveMode);
return SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken);
}
protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int length)
{
// NOTE: There are no errors in crefs - only warnings. We accomplish this by wrapping every diagnostic in ErrorCode.WRN_ErrorOverride.
if (InCref)
{
SyntaxDiagnosticInfo rawInfo = base.GetExpectedTokenError(expected, actual, offset, length);
SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(rawInfo.Offset, rawInfo.Width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code);
return crefInfo;
}
switch (expected)
{
case SyntaxKind.IdentifierToken:
return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_ExpectedIdentifier);
default:
return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual));
}
}
protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual)
{
// NOTE: There are no errors in crefs - only warnings. We accomplish this by wrapping every diagnostic in ErrorCode.WRN_ErrorOverride.
if (InCref)
{
int offset, width;
this.GetDiagnosticSpanForMissingToken(out offset, out width);
return GetExpectedTokenError(expected, actual, offset, width);
}
switch (expected)
{
case SyntaxKind.IdentifierToken:
return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_ExpectedIdentifier);
default:
return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual));
}
}
private TNode WithXmlParseError<TNode>(TNode node, XmlParseErrorCode code) where TNode : CSharpSyntaxNode
{
return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code));
}
private TNode WithXmlParseError<TNode>(TNode node, XmlParseErrorCode code, params string[] args) where TNode : CSharpSyntaxNode
{
return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code, args));
}
private SyntaxToken WithXmlParseError(SyntaxToken node, XmlParseErrorCode code, params string[] args)
{
return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code, args));
}
protected override TNode WithAdditionalDiagnostics<TNode>(TNode node, params DiagnosticInfo[] diagnostics)
{
// Don't attach any diagnostics to syntax nodes within a documentation comment if the DocumentationMode
// is not at least Diagnose.
return Options.DocumentationMode >= DocumentationMode.Diagnose
? base.WithAdditionalDiagnostics<TNode>(node, diagnostics)
: node;
}
#region Cref
/// <summary>
/// ACASEY: This grammar is derived from the behavior and sources of the native compiler.
/// Tokens start with underscores (I've cheated for _PredefinedTypeToken, which is not actually a
/// SyntaxKind), "*" indicates "0 or more", "?" indicates "0 or 1", and parentheses are for grouping.
///
/// Cref = CrefType _DotToken CrefMember
/// | CrefType
/// | CrefMember
/// | CrefFirstType _OpenParenToken CrefParameterList? _CloseParenToken
/// CrefName = _IdentifierToken (_LessThanToken _IdentifierToken (_CommaToken _IdentifierToken)* _GreaterThanToken)?
/// CrefFirstType = ((_IdentifierToken _ColonColonToken)? CrefName)
/// | _PredefinedTypeToken
/// CrefType = CrefFirstType (_DotToken CrefName)*
/// CrefMember = CrefName (_OpenParenToken CrefParameterList? _CloseParenToken)?
/// | _ThisKeyword (_OpenBracketToken CrefParameterList _CloseBracketToken)?
/// | _OperatorKeyword _OperatorToken (_OpenParenToken CrefParameterList? _CloseParenToken)?
/// | (_ImplicitKeyword | _ExplicitKeyword) _OperatorKeyword CrefParameterType (_OpenParenToken CrefParameterList? _CloseParenToken)?
/// CrefParameterList = CrefParameter (_CommaToken CrefParameter)*
/// CrefParameter = (_RefKeyword | _OutKeyword)? CrefParameterType
/// CrefParameterType = CrefParameterType2 _QuestionToken? _AsteriskToken* (_OpenBracketToken _CommaToken* _CloseBracketToken)*
/// CrefParameterType2 = (((_IdentifierToken _ColonColonToken)? CrefParameterType3) | _PredefinedTypeToken) (_DotToken CrefParameterType3)*
/// CrefParameterType3 = _IdentifierToken (_LessThanToken CrefParameterType (_CommaToken CrefParameterType)* _GreaterThanToken)?
///
/// NOTE: type parameters, not type arguments
/// NOTE: the first production of Cref is preferred to the other two
/// NOTE: pointer, array, and nullable types only work in parameters
/// NOTE: CrefParameterType2 and CrefParameterType3 correspond to CrefType and CrefName, respectively.
/// Since the only difference is that they accept non-identifier type arguments, this is accomplished
/// using parameters on the parsing methods (rather than whole new methods).
/// </summary>
private CrefSyntax ParseCrefAttributeValue()
{
CrefSyntax result;
TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: true, checkForMember: true);
if (type == null)
{
result = ParseMemberCref();
}
else if (IsEndOfCrefAttribute)
{
result = SyntaxFactory.TypeCref(type);
}
else if (type.Kind != SyntaxKind.QualifiedName && this.CurrentToken.Kind == SyntaxKind.OpenParenToken)
{
// Special case for crefs like "string()" and "A::B()".
CrefParameterListSyntax parameters = ParseCrefParameterList();
result = SyntaxFactory.NameMemberCref(type, parameters);
}
else
{
SyntaxToken dot = EatToken(SyntaxKind.DotToken);
MemberCrefSyntax member = ParseMemberCref();
result = SyntaxFactory.QualifiedCref(type, dot, member);
}
bool needOverallError = !IsEndOfCrefAttribute || result.ContainsDiagnostics;
if (!IsEndOfCrefAttribute)
{
var badTokens = _pool.Allocate<SyntaxToken>();
while (!IsEndOfCrefAttribute)
{
badTokens.Add(this.EatToken());
}
result = AddTrailingSkippedSyntax(result, badTokens.ToListNode());
_pool.Free(badTokens);
}
if (needOverallError)
{
result = this.AddError(result, ErrorCode.WRN_BadXMLRefSyntax, result.ToFullString());
}
return result;
}
/// <summary>
/// Parse the custom cref syntax for a named member (method, property, etc),
/// an indexer, an overloadable operator, or a user-defined conversion.
/// </summary>
private MemberCrefSyntax ParseMemberCref()
{
switch (CurrentToken.Kind)
{
case SyntaxKind.ThisKeyword:
return ParseIndexerMemberCref();
case SyntaxKind.OperatorKeyword:
return ParseOperatorMemberCref();
case SyntaxKind.ExplicitKeyword:
case SyntaxKind.ImplicitKeyword:
return ParseConversionOperatorMemberCref();
default:
return ParseNameMemberCref();
}
}
/// <summary>
/// Parse a named member (method, property, etc), with optional type
/// parameters and regular parameters.
/// </summary>
private NameMemberCrefSyntax ParseNameMemberCref()
{
SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers: true);
CrefParameterListSyntax parameters = ParseCrefParameterList();
return SyntaxFactory.NameMemberCref(name, parameters);
}
/// <summary>
/// Parse an indexer member, with optional parameters.
/// </summary>
private IndexerMemberCrefSyntax ParseIndexerMemberCref()
{
Debug.Assert(CurrentToken.Kind == SyntaxKind.ThisKeyword);
SyntaxToken thisKeyword = EatToken();
CrefBracketedParameterListSyntax parameters = ParseBracketedCrefParameterList();
return SyntaxFactory.IndexerMemberCref(thisKeyword, parameters);
}
/// <summary>
/// Parse an overloadable operator, with optional parameters.
/// </summary>
private OperatorMemberCrefSyntax ParseOperatorMemberCref()
{
Debug.Assert(CurrentToken.Kind == SyntaxKind.OperatorKeyword);
SyntaxToken operatorKeyword = EatToken();
SyntaxToken operatorToken;
if (SyntaxFacts.IsAnyOverloadableOperator(CurrentToken.Kind))
{
operatorToken = EatToken();
}
else
{
operatorToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken);
// Grab the offset and width before we consume the invalid keyword and change our position.
int offset;
int width;
GetDiagnosticSpanForMissingToken(out offset, out width);
if (SyntaxFacts.IsUnaryOperatorDeclarationToken(CurrentToken.Kind) || SyntaxFacts.IsBinaryExpressionOperatorToken(CurrentToken.Kind))
{
operatorToken = AddTrailingSkippedSyntax(operatorToken, EatToken());
}
SyntaxDiagnosticInfo rawInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected);
SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code);
operatorToken = WithAdditionalDiagnostics(operatorToken, crefInfo);
}
// Have to fake >> because it looks like the closing of nested type parameter lists (e.g. A<A<T>>).
// Have to fake >= so the lexer doesn't mishandle >>=.
if (operatorToken.Kind == SyntaxKind.GreaterThanToken && operatorToken.GetTrailingTriviaWidth() == 0 && CurrentToken.GetLeadingTriviaWidth() == 0)
{
if (CurrentToken.Kind == SyntaxKind.GreaterThanToken)
{
var operatorToken2 = this.EatToken();
operatorToken = SyntaxFactory.Token(
operatorToken.GetLeadingTrivia(),
SyntaxKind.GreaterThanGreaterThanToken,
operatorToken.Text + operatorToken2.Text,
operatorToken.ValueText + operatorToken2.ValueText,
operatorToken2.GetTrailingTrivia());
}
else if (CurrentToken.Kind == SyntaxKind.EqualsToken)
{
var operatorToken2 = this.EatToken();
operatorToken = SyntaxFactory.Token(
operatorToken.GetLeadingTrivia(),
SyntaxKind.GreaterThanEqualsToken,
operatorToken.Text + operatorToken2.Text,
operatorToken.ValueText + operatorToken2.ValueText,
operatorToken2.GetTrailingTrivia());
}
else if (CurrentToken.Kind == SyntaxKind.GreaterThanEqualsToken)
{
var operatorToken2 = this.EatToken();
var nonOverloadableOperator = SyntaxFactory.Token(
operatorToken.GetLeadingTrivia(),
SyntaxKind.GreaterThanGreaterThanEqualsToken,
operatorToken.Text + operatorToken2.Text,
operatorToken.ValueText + operatorToken2.ValueText,
operatorToken2.GetTrailingTrivia());
operatorToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken);
// Add non-overloadable operator as skipped token.
operatorToken = AddTrailingSkippedSyntax(operatorToken, nonOverloadableOperator);
// Add an appropriate diagnostic.
const int offset = 0;
int width = nonOverloadableOperator.Width;
SyntaxDiagnosticInfo rawInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected);
SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code);
operatorToken = WithAdditionalDiagnostics(operatorToken, crefInfo);
}
}
Debug.Assert(SyntaxFacts.IsAnyOverloadableOperator(operatorToken.Kind));
CrefParameterListSyntax parameters = ParseCrefParameterList();
return SyntaxFactory.OperatorMemberCref(operatorKeyword, operatorToken, parameters);
}
/// <summary>
/// Parse a user-defined conversion, with optional parameters.
/// </summary>
private ConversionOperatorMemberCrefSyntax ParseConversionOperatorMemberCref()
{
Debug.Assert(CurrentToken.Kind == SyntaxKind.ExplicitKeyword ||
CurrentToken.Kind == SyntaxKind.ImplicitKeyword);
SyntaxToken implicitOrExplicit = EatToken();
SyntaxToken operatorKeyword = EatToken(SyntaxKind.OperatorKeyword);
TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false);
CrefParameterListSyntax parameters = ParseCrefParameterList();
return SyntaxFactory.ConversionOperatorMemberCref(implicitOrExplicit, operatorKeyword, type, parameters);
}
/// <summary>
/// Parse a parenthesized parameter list.
/// </summary>
private CrefParameterListSyntax ParseCrefParameterList()
{
return (CrefParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: false);
}
/// <summary>
/// Parse a bracketed parameter list.
/// </summary>
private CrefBracketedParameterListSyntax ParseBracketedCrefParameterList()
{
return (CrefBracketedParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: true);
}
/// <summary>
/// Parse the parameter list (if any) of a cref member (name, indexer, operator, or conversion).
/// </summary>
private BaseCrefParameterListSyntax ParseBaseCrefParameterList(bool useSquareBrackets)
{
SyntaxKind openKind = useSquareBrackets ? SyntaxKind.OpenBracketToken : SyntaxKind.OpenParenToken;
SyntaxKind closeKind = useSquareBrackets ? SyntaxKind.CloseBracketToken : SyntaxKind.CloseParenToken;
if (CurrentToken.Kind != openKind)
{
return null;
}
SyntaxToken open = EatToken(openKind);
var list = _pool.AllocateSeparated<CrefParameterSyntax>();
try
{
while (CurrentToken.Kind == SyntaxKind.CommaToken || IsPossibleCrefParameter())
{
list.Add(ParseCrefParameter());
if (CurrentToken.Kind != closeKind)
{
SyntaxToken comma = EatToken(SyntaxKind.CommaToken);
if (!comma.IsMissing || IsPossibleCrefParameter())
{
// Only do this if it won't be last in the list.
list.AddSeparator(comma);
}
else
{
// How could this scenario arise? If it does, just expand the if-condition.
Debug.Assert(CurrentToken.Kind != SyntaxKind.CommaToken);
}
}
}
// NOTE: nothing follows a cref parameter list, so there's no reason to recover here.
// Just let the cref-level recovery code handle any remaining tokens.
SyntaxToken close = EatToken(closeKind);
return useSquareBrackets
? (BaseCrefParameterListSyntax)SyntaxFactory.CrefBracketedParameterList(open, list, close)
: SyntaxFactory.CrefParameterList(open, list, close);
}
finally
{
_pool.Free(list);
}
}
/// <summary>
/// True if the current token could be the beginning of a cref parameter.
/// </summary>
private bool IsPossibleCrefParameter()
{
SyntaxKind kind = this.CurrentToken.Kind;
switch (kind)
{
case SyntaxKind.RefKeyword:
case SyntaxKind.OutKeyword:
case SyntaxKind.InKeyword:
case SyntaxKind.IdentifierToken:
return true;
default:
return SyntaxFacts.IsPredefinedType(kind);
}
}
/// <summary>
/// Parse an element of a cref parameter list.
/// </summary>
/// <remarks>
/// "ref" and "out" work, but "params", "this", and "__arglist" don't.
/// </remarks>
private CrefParameterSyntax ParseCrefParameter()
{
SyntaxToken refKindOpt = null;
switch (CurrentToken.Kind)
{
case SyntaxKind.RefKeyword:
case SyntaxKind.OutKeyword:
case SyntaxKind.InKeyword:
refKindOpt = EatToken();
break;
}
TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false);
return SyntaxFactory.CrefParameter(refKindOpt, type);
}
/// <summary>
/// Parse an identifier, optionally followed by an angle-bracketed list of type parameters.
/// </summary>
/// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier
/// type argument is seen, false to accept. No change in the shape of the tree.</param>
private SimpleNameSyntax ParseCrefName(bool typeArgumentsMustBeIdentifiers)
{
SyntaxToken identifierToken = EatToken(SyntaxKind.IdentifierToken);
if (CurrentToken.Kind != SyntaxKind.LessThanToken)
{
return SyntaxFactory.IdentifierName(identifierToken);
}
var open = EatToken();
var list = _pool.AllocateSeparated<TypeSyntax>();
try
{
while (true)
{
TypeSyntax typeSyntax = ParseCrefType(typeArgumentsMustBeIdentifiers);
if (typeArgumentsMustBeIdentifiers && typeSyntax.Kind != SyntaxKind.IdentifierName)
{
typeSyntax = this.AddError(typeSyntax, ErrorCode.WRN_ErrorOverride,
new SyntaxDiagnosticInfo(ErrorCode.ERR_TypeParamMustBeIdentifier), $"{(int)ErrorCode.ERR_TypeParamMustBeIdentifier:d4}");
}
list.Add(typeSyntax);
var currentKind = CurrentToken.Kind;
if (currentKind == SyntaxKind.CommaToken || currentKind == SyntaxKind.IdentifierToken ||
SyntaxFacts.IsPredefinedType(CurrentToken.Kind))
{
// NOTE: if the current token is an identifier or predefined type, then we're
// actually inserting a missing commas.
list.AddSeparator(EatToken(SyntaxKind.CommaToken));
}
else
{
break;
}
}
SyntaxToken close = EatToken(SyntaxKind.GreaterThanToken);
open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics, forceWarning: true);
return SyntaxFactory.GenericName(identifierToken, SyntaxFactory.TypeArgumentList(open, list, close));
}
finally
{
_pool.Free(list);
}
}
/// <summary>
/// Parse a type. May include an alias, a predefined type, and/or a qualified name.
/// </summary>
/// <remarks>
/// Pointer, nullable, or array types are only allowed if <paramref name="typeArgumentsMustBeIdentifiers"/> is false.
/// Leaves a dot and a name unconsumed if the name is not followed by another dot
/// and checkForMember is true.
/// </remarks>
/// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier
/// type argument is seen, false to accept. No change in the shape of the tree.</param>
/// <param name="checkForMember">True means that the last name should not be consumed
/// if it is followed by a parameter list.</param>
private TypeSyntax ParseCrefType(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false)
{
TypeSyntax typeWithoutSuffix = ParseCrefTypeHelper(typeArgumentsMustBeIdentifiers, checkForMember);
return typeArgumentsMustBeIdentifiers
? typeWithoutSuffix
: ParseCrefTypeSuffix(typeWithoutSuffix);
}
/// <summary>
/// Parse a type. May include an alias, a predefined type, and/or a qualified name.
/// </summary>
/// <remarks>
/// No pointer, nullable, or array types.
/// Leaves a dot and a name unconsumed if the name is not followed by another dot
/// and checkForMember is true.
/// </remarks>
/// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier
/// type argument is seen, false to accept. No change in the shape of the tree.</param>
/// <param name="checkForMember">True means that the last name should not be consumed
/// if it is followed by a parameter list.</param>
private TypeSyntax ParseCrefTypeHelper(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false)
{
NameSyntax leftName;
if (SyntaxFacts.IsPredefinedType(CurrentToken.Kind))
{
// e.g. "int"
// NOTE: a predefined type will not fit into a NameSyntax, so we'll return
// immediately. The upshot is that you can only dot into a predefined type
// once (e.g. not "int.A.B"), which is fine because we know that none of them
// have nested types.
return SyntaxFactory.PredefinedType(EatToken());
}
else if (CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.ColonColonToken)
{
// e.g. "A::B"
SyntaxToken alias = EatToken();
if (alias.ContextualKind == SyntaxKind.GlobalKeyword)
{
alias = ConvertToKeyword(alias);
}
alias = CheckFeatureAvailability(alias, MessageID.IDS_FeatureGlobalNamespace, forceWarning: true);
SyntaxToken colonColon = EatToken();
SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers);
leftName = SyntaxFactory.AliasQualifiedName(SyntaxFactory.IdentifierName(alias), colonColon, name);
}
else
{
// e.g. "A"
ResetPoint resetPoint = GetResetPoint();
leftName = ParseCrefName(typeArgumentsMustBeIdentifiers);
if (checkForMember && (leftName.IsMissing || CurrentToken.Kind != SyntaxKind.DotToken))
{
// If this isn't the first part of a dotted name, then we prefer to represent it
// as a MemberCrefSyntax.
this.Reset(ref resetPoint);
this.Release(ref resetPoint);
return null;
}
this.Release(ref resetPoint);
}
while (CurrentToken.Kind == SyntaxKind.DotToken)
{
// NOTE: we make a lot of these, but we'll reset, at most, one time.
ResetPoint resetPoint = GetResetPoint();
SyntaxToken dot = EatToken();
SimpleNameSyntax rightName = ParseCrefName(typeArgumentsMustBeIdentifiers);
if (checkForMember && (rightName.IsMissing || CurrentToken.Kind != SyntaxKind.DotToken))
{
this.Reset(ref resetPoint); // Go back to before the dot - it must have been the trailing dot.
this.Release(ref resetPoint);
return leftName;
}
this.Release(ref resetPoint);
leftName = SyntaxFactory.QualifiedName(leftName, dot, rightName);
}
return leftName;
}
/// <summary>
/// Once the name part of a type (including type parameter/argument lists) is parsed,
/// we need to consume ?, *, and rank specifiers.
/// </summary>
private TypeSyntax ParseCrefTypeSuffix(TypeSyntax type)
{
if (CurrentToken.Kind == SyntaxKind.QuestionToken)
{
type = SyntaxFactory.NullableType(type, EatToken());
}
while (CurrentToken.Kind == SyntaxKind.AsteriskToken)
{
type = SyntaxFactory.PointerType(type, EatToken());
}
if (CurrentToken.Kind == SyntaxKind.OpenBracketToken)
{
var omittedArraySizeExpressionInstance = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken));
var rankList = _pool.Allocate<ArrayRankSpecifierSyntax>();
try
{
while (CurrentToken.Kind == SyntaxKind.OpenBracketToken)
{
SyntaxToken open = EatToken();
var dimensionList = _pool.AllocateSeparated<ExpressionSyntax>();
try
{
while (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken)
{
if (this.CurrentToken.Kind == SyntaxKind.CommaToken)
{
// NOTE: trivia will be attached to comma, not omitted array size
dimensionList.Add(omittedArraySizeExpressionInstance);
dimensionList.AddSeparator(this.EatToken());
}
else
{
// CONSIDER: if we expect people to try to put expressions in between
// the commas, then it might be more reasonable to recover by skipping
// tokens until we hit a CloseBracketToken (or some other terminator).
break;
}
}
// Don't end on a comma.
// If the omitted size would be the only element, then skip it unless sizes were expected.
if ((dimensionList.Count & 1) == 0)
{
dimensionList.Add(omittedArraySizeExpressionInstance);
}
// Eat the close brace and we're done.
var close = this.EatToken(SyntaxKind.CloseBracketToken);
rankList.Add(SyntaxFactory.ArrayRankSpecifier(open, dimensionList, close));
}
finally
{
_pool.Free(dimensionList);
}
}
type = SyntaxFactory.ArrayType(type, rankList);
}
finally
{
_pool.Free(rankList);
}
}
return type;
}
/// <summary>
/// Ends at appropriate quotation mark, EOF, or EndOfDocumentationComment.
/// </summary>
private bool IsEndOfCrefAttribute
{
get
{
switch (CurrentToken.Kind)
{
case SyntaxKind.SingleQuoteToken:
return (this.Mode & LexerMode.XmlCrefQuote) == LexerMode.XmlCrefQuote;
case SyntaxKind.DoubleQuoteToken:
return (this.Mode & LexerMode.XmlCrefDoubleQuote) == LexerMode.XmlCrefDoubleQuote;
case SyntaxKind.EndOfFileToken:
case SyntaxKind.EndOfDocumentationCommentToken:
return true;
case SyntaxKind.BadToken:
// If it's a real '<' (not <, etc), then we assume it's the beginning
// of the next XML element.
return CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken) ||
IsNonAsciiQuotationMark(CurrentToken);
default:
return false;
}
}
}
/// <summary>
/// Convenience method for checking the mode.
/// </summary>
private bool InCref
{
get
{
switch (this.Mode & (LexerMode.XmlCrefDoubleQuote | LexerMode.XmlCrefQuote))
{
case LexerMode.XmlCrefQuote:
case LexerMode.XmlCrefDoubleQuote:
return true;
default:
return false;
}
}
}
#endregion Cref
#region Name attribute values
private IdentifierNameSyntax ParseNameAttributeValue()
{
// Never report a parse error - just fail to bind the name later on.
SyntaxToken identifierToken = this.EatToken(SyntaxKind.IdentifierToken, reportError: false);
if (!IsEndOfNameAttribute)
{
var badTokens = _pool.Allocate<SyntaxToken>();
while (!IsEndOfNameAttribute)
{
badTokens.Add(this.EatToken());
}
identifierToken = AddTrailingSkippedSyntax(identifierToken, badTokens.ToListNode());
_pool.Free(badTokens);
}
return SyntaxFactory.IdentifierName(identifierToken);
}
/// <summary>
/// Ends at appropriate quotation mark, EOF, or EndOfDocumentationComment.
/// </summary>
private bool IsEndOfNameAttribute
{
get
{
switch (CurrentToken.Kind)
{
case SyntaxKind.SingleQuoteToken:
return (this.Mode & LexerMode.XmlNameQuote) == LexerMode.XmlNameQuote;
case SyntaxKind.DoubleQuoteToken:
return (this.Mode & LexerMode.XmlNameDoubleQuote) == LexerMode.XmlNameDoubleQuote;
case SyntaxKind.EndOfFileToken:
case SyntaxKind.EndOfDocumentationCommentToken:
return true;
case SyntaxKind.BadToken:
// If it's a real '<' (not <, etc), then we assume it's the beginning
// of the next XML element.
return CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken) ||
IsNonAsciiQuotationMark(CurrentToken);
default:
return false;
}
}
}
#endregion Name attribute values
}
}
| -1 |
dotnet/roslyn | 56,424 | EnC/HR interface unification | Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | tmat | "2021-09-15T22:22:11Z" | "2021-09-21T16:03:37Z" | 8574e338076f0a2d7a4bc0d129f00e7440e47fbb | 240a47028f8518833271b026667f18f2c02fcbd8 | EnC/HR interface unification. Prepares for unification of EnC and Hot Reload debugger interfaces. In this PR we still implement two separate MEF components that delegate to a common implementation. These will be eliminated in vs-deps follow up.
Contributes to
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1363800
https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1407091
Fixes https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_queries/edit/1398619 | ./src/Compilers/Test/Resources/Core/SymbolsTests/ExplicitInterfaceImplementation/CSharpExplicitInterfaceImplementation.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L (M ! + @ @ @ X+ S @ ` H .text `.rsrc @ @ @.reloc ` @ B + H d
*(
*
*
*
*
* 0
+ *
*(
*
*
*
*
* 0
+ *
*(
*
*(
*(
*
*(
*
*(
*
*(
*
*(
* BSJB v4.0.30319 l #~ P #Strings d #US l #GUID | #Blob G
%3 $ '
$
4 > D O
Y e y ! # = P = S = A J Q Z d n
[ A ^ J a Q d Z h d { n ~ = +w + + + + + = " = " = " " = # # K $ = % _ % = & |